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.
Follow up:
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?
給定字符串s和t,判斷s是否是t的子序列。
這里假定s和t都只含有小寫字母,t可以是非常長的字符串(長度約為500,000),s是短字符串(長度小于100)。
注意子序列是由原生序列中的某些元素按照相對位置不變的狀態(tài)組成的新序列。
進(jìn)階:若輸入的待檢測短序列s有很多個(gè),而你又想一個(gè)一個(gè)檢測是否為t的子序列,如何改寫你的代碼?
思路
簡單的做法,t中依次對s的首個(gè)字母進(jìn)行匹配,成功則匹配s的下一個(gè)字母,直到s被匹配完成(返回true)或t掃描結(jié)束且s仍未匹配完(返回false),這里注意,對于s為空的情況,總是匹配為true。
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.size()>t.size()) return false;
if(s=="") return true;
for(auto sit=s.begin(),tit=t.begin(); tit!=t.end();tit++){
if(*sit==*tit) sit++;
if(sit==s.end()) return true;
}
return false;
}
};