原题链接:Leetcode 392. 判断子序列
解法一:
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s == t)
return true;
int lens = s.size();
int lent = t.size();
int i = 0, j = 0;
while (i < lent) {
int pre = i;
while (i < lent && j < lens) {
if (t[i] == s[j]) {
j++;
}
i++;
}
if (j == lens)
return true;
i = pre + 1;
j = 0;
}
return false;
}
};
解法一的贪心优化:
贪心思路,参考官解:Leetcode 392. 判断子序列
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s == t)
return true;
int lens = s.size();
int lent = t.size();
int i = 0, j = 0;
while (i < lent && j < lens) {
if (t[i] == s[j]) {
j++;
}
i++;
}
if (j == lens) return true;
return false;
}
};