You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 Is Subsequence 🔥 || 5 Approaches || Simple Fast and Easy || with Explanation
Solution - 1
classSolution {
boolisSubsequence(String s, String t) {
if (s.length > t.length) returnfalse;
int j =0;
for (int i =0; i < t.length && j < s.length; i++) {
if (s[j] == t[i]) {
j++;
}
}
if (j == t.length) returntrue;
returnfalse;
}
}
Solution - 2
classSolution {
boolisSubString(String s, String t, int m, int n) {
if (m ==0) returntrue;
if (n ==0) returnfalse;
// If last characters of two// strings are matchingif (s[m -1] == t[n -1]) returnisSubString(s, t, m -1, n -1);
// If last characters are// not matchingreturnisSubString(s, t, m, n -1);
}
boolisSubsequence(String s, String t) {
if (isSubString(s, t, s.length, t.length)) returntrue;
returnfalse;
}
}
Solution - 3
classSolution {
intisSubs(String s1, String s2, int i, int j, List<List<int>> t) {
if (i ==0|| j ==0) return0;
if (t[i][j] !=-1) return t[i][j];
if (s1[i -1] == s2[j -1])
return t[i][j] =1+isSubs(s1, s2, i -1, j -1, t);
elsereturn t[i][j] =isSubs(s1, s2, i, j -1, t);
}
boolisSubsequence(String s, String t) {
int m = s.length;
int n = t.length;
// initializing dp matrix with -1if (m > n) returnfalse;
List<List<int>> f =List.filled(m +1, 0).map((e) =>List.filled(n +1, -1)).toList();
if (isSubs(s, t, m, n, f) == m) returntrue;
returnfalse;
}
}
Solution - 4
classSolution {
boolisSubsequence(String s, String t) {
for (int x = t.length -1; x >=0&& s.isNotEmpty; x--)
if (t[x] == s[s.length -1])
s.split("").removeLast(); //treating subsequence string as a stackreturn s.isEmpty;
}
}
Solution - 5
classSolution {
boolisSubsequence(String s, String t) {
int p1 =0;
int p2 =0;
while (p1 < s.length) {
while (p2 < t.length) {
if (s[p1] == t[p2]) break;
p2++;
}
if (p2 == t.length) returnfalse;
p1++;
p2++;
}
returntrue;
}
}