题目:
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:
输入:s = "axc", t = "ahbgdc"
输出:false
思路一:
遍历s,假设字符为c1,t中如果不存在c1直接返回false。如果存在t截取c1在t中所在位置的后半段。
代码如下:
public boolean isSubsequence(String s, String t) {
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
if (t.indexOf(c1) == -1)
return false;
t = t.substring(t.indexOf(c1) + 1);
}
return true;
}
思路二:
双指针,申明i为s指针,j为t的指针。
当i<s.length 和 j<t.length时,如果s.charAt(i)==t.charAt(j),说明t中存在s当前字符。不管有无j++,j继续向后寻找。
当i==s.length时,说明找到了最后,返回true
代码如下:
public boolean isSubsequence1(String s, String t) {
int i = 0, j = 0;
int n = s.length(), m = t.length();
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
i++;
}
j++;
}
return i == n;
}
-------------------------------小白学算法