题目:
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;
}
};