Is One String a Subsequence of Another
Problem
Given two strings s and t, decide whether every character of s appears in t in the same order (not necessarily contiguous). Walk both strings together; advance the s pointer only when the current characters match.
Input
s = "ace", t = "abcde"Output
truea, c, e appear at indices 0, 2, 4 in t.
def is_subsequence(s, t):
i = 0
for ch in t:
if i < len(s) and ch == s[i]:
i += 1
return i == len(s)
function isSubsequence(s, t) {
let i = 0;
for (let j = 0; j < t.length && i < s.length; j++) {
if (t[j] === s[i]) i++;
}
return i === s.length;
}
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0;
for (int j = 0; j < t.length() && i < s.length(); j++) {
if (t.charAt(j) == s.charAt(i)) i++;
}
return i == s.length();
}
}
bool isSubsequence(string s, string t) {
int i = 0;
for (int j = 0; j < (int)t.size() && i < (int)s.size(); j++) {
if (t[j] == s[i]) i++;
}
return i == (int)s.size();
}