分析
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
输入:s = “abc”, t = “ahbgdc”
输出:true
题目
这道题目可以遍历s也可以遍历t,遍历s时间复杂度可能更低一点,遍历期间就是要判断s的顺序是否和t保持一致即可
public class isSubsequence {
public static void main(String[] args) {
String s = "axc";
String t = "ahbgdc";
System.out.println(isSub(s,t));
}
public static boolean isSub(String s,String t) {
int j = 0;
for(int i = 0;i<s.length();i++) {
while(j < t.length() && t.charAt(j) != s.charAt(i)) {
j++;
}
if(j >= t.length() || t.length() - j < s.length() - i) {
return false;
} else {
j = j + 1;
}
}
return true;
}
}
5471



被折叠的 条评论
为什么被折叠?



