題目:Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).
Example 1:
s = “abc”, t = “ahbgdc”
Return true.
Example 2:
s = “axc”, t = “ahbgdc”
Return false.
難度:medium 通過率:43.8%
這道題想法比較簡單,直接對兩個字符串進行對比判斷,通過一個while循環語句就可以寫出來,用count按順序記錄相同的個數,就可以得出結果。實現如下:算法複雜度:O(n)
class Solution {
public:
bool isSubsequence(string s, string t) {
int count = 0;
int i = 0, j = 0;
while(i < s.length() && j < t.length()) {
if(s[i] == t[j]) {
count++;
i++;
}
j++;
}
if(count == s.length()) return true;
return false;
}
};