这里写自定义目录标题
2023-8-24 18:53:25
class Solution {
public boolean isSubsequence(String s, String t) {
int sIndex = 0;
// 遍历原始字符串
for (int i = 0; i < t.length(); i++) {
// 子字符串的下标 已经等于 子字符串的长度
// 已经遍历完s了,即 's 是 t 的子序列'
if (sIndex == s.length() ) {
return true;
}
// 如果s的字符等于t的字符
if (t.charAt(i) == s.charAt(sIndex)) {
// 可以去找s的下一个下标
sIndex++;
}
}
// 已经遍历完s下标了,即能够找到符合的新字符串
if (sIndex == s.length() ) {
return true;
}
return false;
}
}
官方的双指针解法比我写的优秀啊
public boolean isSubsequence(String s, String t) {
int sLength = s.length(), tLength = t.length();
int sIndex = 0, tIndex = 0;
while (sIndex < sLength && tIndex < tLength) {
if (s.charAt(sIndex) == t.charAt(tIndex)) {
sIndex++;
}
tIndex++;
}
return sIndex == sLength;
}