392. Is Subsequence
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
.
class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.size();
int m = t.size();
vector<vector<int>>dp (n+1,vector<int>(m+1));
for(int i = 0 ; i <= n ; i ++){
for(int j = 0 ; j <= m; j ++){
if(i == 0 || j == 0 ){
dp[i][j] = 0 ;
}else if(s[i-1] == t[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}else {
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
}
}
}
if(dp[n][m] == n ){
return true ;
}else{
return false;
}
}
};
解法二:簡單考慮,直接用兩個for循環去遍歷即可:
class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.size();
int m = t.size();
int pos = 0;
for(int i = 0 ; i < n ; i ++){
bool flag = false;
for(int j = pos ; j<m; j++){
if(s[i] == t[j]){
pos = j+1;
flag = true;
break;
}
}
if(flag == false)
return false;
}
return true;
}
};