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
.
挑战
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
解题思路:
遍历一遍t,如果两指针指向的值相等,则同时加加,继续考察下一组元素,否则只加pt,最后若ps指向末尾了,说明true,否则为false。
class Solution {
public:
/**
* @param s: the given string s
* @param t: the given string t
* @return: check if s is subsequence of t
*/
bool isSubsequence(string &s, string &t)
{
// Write your code here
if(s.empty())
return true;
for(int pt = 0,ps = 0;pt < t.size();pt++)
{
if(s[ps] == t[pt])
ps++;
if(ps == s.size())
return true;
}
return false;
}
};