Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "<u>a</u>b<u>c</u>d<u>e</u>" while "aec" is not).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Constraints:
0 <= s.length <= 1000 <= t.length <= 104sandtconsist only of lowercase English letters.`
Double pointers or DP.
// double pointers
class Solution {
public:
bool isSubsequence(string s, string t) {
int n1 = s.size(), n2 = t.size();
if (n1 > n2) return false;
if (n1 == 0) return true;
int left = 0, right = 0;
while (left < n1 && right < n2) {
if (s[left] == t[right]) {
left++;
right++;
}
else right++;
}
return left == n1;
}
};
// DP
class Solution {
public:
bool isSubsequence(string s, string t) {
vector<vector<int>> dp(s.size() + 1, vector<int>(t.size() + 1, 0));
for (int i = 1; i <= s.size(); i++) {
for (int j = 1; j <= t.size(); j++) {
if (s[i - 1] == t[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = dp[i][j - 1]; // delete t[j-1]
}
}
if (dp[s.size()][t.size()] == s.size()) return true;
return false;
}
};