392. 判断子序列
方法一
class Solution {
public:
bool isSubsequence(string s, string t) {
int top = 0, bottom = 0;
int tlength = t.length(), slength = s.length();
if(slength == 0){
return true;
}
while(top < tlength){
if(s[bottom] == t[top]){
bottom++;
}
if(bottom == slength){
return true;
}
top++;
}
return false;
}
};
class Solution {
public:
bool isSubsequence(string s, string t) {
int top = 0, bottom = 0;
int tlength = t.length(), slength = s.length();
while(top < tlength && bottom < slength){
if(s[bottom] == t[top]){
bottom++;
}
top++;
}
return bottom == slength;
}
};
方法二
class Solution {
public:
bool isSubsequence(string s, string t){
int n = s.length(),m = t.length();
vector<vector<int>> dp(m + 1,vector<int> (26,0));
for(int i=0;i<26;i++){
dp[m][i] = m;
}
for(int i = m - 1;i>=0;i--) {
for(int j=0;j<26;j++){
if(t[i] == 'a' + j){
dp[i][j] = i;
}else {
dp[i][j] = dp[i + 1][j];
}
}
}
int add = 0;
for(int i = 0;i<n;i++){
if(dp[add][s[i] - 'a'] == m){
return false;
}
add = dp[add][s[i] - 'a'] + 1;
}
return true;
}
};