Problem
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 "abcde"
while "aec"
is not).
Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s
andt
consist only of lowercase English letters.
Solution
c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool subsequence_strings::isSubsequence(string s, string t) {
int sl = s.length();
int tl = t.length();
if (sl > tl) {
return false;
}
int j = 0;
for (int i = 0; i < sl; ++i) {
char sc = s[i];
while (j < tl && t[j] != sc) {
j++;
}
if (j >= tl) {
return false;
}
j++;
}
return true;
}
References
https://leetcode.com/problems/is-subsequence/?envType=study-plan&id=level-1