LeetCode: Is Subsequence
題目:
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.
題目要求我們判斷s是不是t的子序列,即s中的元素都在t中出現,且出現的順序相同。由於t的最大長度為500000,s的最大長度為100,如果使用窮搜演算法,演算法很容易超時,而t的序列又是固定的(不可以重新排序),所以搜尋一個字母是不是在t中的複雜度很難達到o(logn),演算法的時間複雜度很難達到o(mlogn),m為s的長度,n為t的長度。所以,要尋求一個更高效的演算法。
演算法:直接從s和t的下標為0處開始遍歷,如果是s[i]=t[j],則i和j同時加一;否則j加一,i不加一。如果i先到達s的長度,則說明s是t的子序列;如果j先到達t的長度,則說明s不是t的子序列。演算法的時間複雜度為o(n),n為t的長度。Accepted的程式碼:
class Solution {
public:
bool isSubsequence(string s, string t) {
int i=0;
int j=0;
while(i!=s.length()&&j!=t.length())
{
if(s[i]==t[j])
{
i++;
j++;
}
else j++;
}
if (i==s.length()) return true;
else return false;
}
};