解题思路:
使用贪心算法,每在字符串t中找到s的相应顺序的一个字符,就当做找到了该字符,然后接着去找后面的字符。
程序大循环:在字符串 t 中去寻找字符串 s 的第一个字符。
每当找到 s 的起始字符,就开始用贪心的思想去匹配字符串 s 和 t 。
class Solution {
public:
bool isSubsequence(string s, string t) {
if(t.empty() && !s.empty()) return false;
if(s.empty()) return true;
for(int i = 0; i < t.length() - s.length() + 1; i++){
if(t[i] == s[0]){ //找到起始字符
int j = i + 1; //指示字符串t中字符位置的指针
int k = 1; //指示字符串s中字符位置的指针
while(j < t.length()){
if(t[j] == s[k]){ //找到一个相同字符,那就将指针位置都加1
j++;
k++;
}
else j++; //没找到,继续看看字符串t中后面的字符
if(k == s.length()) return true; //找完整个字符串s了,提前结束,返回true
}
}
}
return false;
}
};