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?
2 尝试解
2.1 分析
判断字符串t只通过删除操作能否变为字符串s,即s是否为t的子串。
只需两个指针,index_s和index_t,index_t一直向后移动,如果找到了s[index_x],则两者都向后移动一位。如果任意指针到达结尾,则结束程序。判断index_s==s.size()。
如果有多个s,这个方法会比较费时。可以用map<char,vector>记录每个字母出现的所有次序,判断s是否为子串时,变量LastOrder记录上一个配对的字符出现的位置,初始为-1,然后依次找下一个字母出现的次序列表中,是否有比LastOrder更大的次序,如果有,LastOrder取其中的最小次序,然后判断s中的下一个字符,否则返回false。而且由于vector中是按顺序添加的,可以用二分法查找大于LastOrder的最小次序。
2.2 代码
方法一:双遍历
class Solution {
public:
bool isSubsequence(string s, string t) {
int s_index = 0;
int t_index = 0;
while(s_index < s.size() && t_index < t.size()){
while(t_index < t.size() && t[t_index] != s[s_index])
t_index++;
if(t_index < t.size()){
s_index++;
t_index++;
}
}
return s_index == s.size();
}
};
方法二:HashMap 单遍历
class Solution {
public:
bool isSubsequence(string s, string t) {
vector<vector<int>> letter_order(26);
for(int i = 0; i < t.size();i++){
letter_order[t[i]-'a'].push_back(i);
}
int last_order = -1;
for(int i = 0; i < s.size(); i++){
if(!letter_order[s[i]-'a'].size() || letter_order[s[i]-'a'].back() <= last_order )
return false;
for(auto order : letter_order[s[i]-'a']){
if(order > last_order){
last_order = order;
break;
}
}
}
return true;
}
};
3 标准解
bool isSubsequence(string s, string t) {
int sLen = s.length(), sIdx = 0, tLen = t.length();
for (int i=0; i<tLen && sIdx<sLen; i++)
if (t[i]==s[sIdx]) sIdx++;
return sIdx==sLen;
}