Two pointers point to s and t respectively. If they match, both pointers move forward; if not, the pointer pointing to t moves forward. Note that empty strings need to be handled separately.
classSolution { public: boolisSubsequence(string s, string t) { // Determine if s is a subsequence of t int i = 0, j = 0; int s_len = s.size(); int t_len = t.size();
if (s_len == 0) { returntrue; } while (i < s_len && j < t_len) { if (s[i] == t[j]) { i++; } j++; } if (i == s_len && s[i - 1] == t[j - 1]) { returntrue; } returnfalse; } };
#include<stdio.h> intmain() { Solution solution; string s = "abc"; string t = "ahbgdc"; printf("%d\n", solution.isSubsequence(s, t)); }
Dynamic Programming
Considering the previous two-pointer approach, we notice that we spend a lot of time finding the next matching character in t. Thus, we can preprocess for each position in t the first occurrence of each character from that position onward. We can use dynamic programming to implement the preprocessing:
Let f[i][j] denote the first occurrence of character j starting from position i in string t.
During state transition: if the character at position i in t is j, thenf[i][j]=i, otherwise j appears starting from position i+1 onwards, i.e.,f[i][j]=f[i+1][j], therefore we need to construct dp from back to front
The state transition equation is:
f[i][j]={if[i+1][j]t[i]=jt[i]=j
The boundary conditions are:
f[m][j]=m∀j∈{0,1,…,25}
where:
idenotes the stringtposition in (starting from 0, 0 ≤ i ≤ m)
jdenotes the character index (usually ‘a’ corresponds to 0, ‘b’ to 1, …, ‘z’ to 25)
f[i][j]=mdenotes from positionionwards there is no characterj
classSolution { public: boolisSubsequence(string s, string t) { int n = s.size(), m = t.size(); // m+1 is to handle boundary cases vector<vector<int> > f(m + 1, vector<int>(26, 0)); for (int i = 0; i < 26; i++) { f[m][i] = m; }
for (int i = m - 1; i >= 0; i--) { for (int j = 0; j < 26; j++) { if (t[i] == j + 'a') f[i][j] = i; else f[i][j] = f[i + 1][j]; } } int add = 0; for (int i = 0; i < n; i++) { if (f[add][s[i] - 'a'] == m) { returnfalse; } add = f[add][s[i] - 'a'] + 1; } returntrue; } };