如果用遞歸或許可以解決,但是,100也不是個小數字。考慮使用雙指針,一次循環來解決:
class Solution {
public:
bool isSubsequence(string s, string t) {
for(size_t i = 0, j = 0; i < s.length(); ++i, ++j){
while(t[j] != s[i] && j < t.length()){
++j;
}
if(j == t.length())
return false;
}
return true;
}
};
特別注意雙指針的移動,第一次submit的錯誤出現在i++的時候,沒有進行j++,那麼在leetcode可以找出來子串leeeeeetcode,因爲e會判斷多次。