Description
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).
Example 1:
|
|
Example 2:
|
|
Constraints:
0 <= s.length <= 100
0 <= t.length <= 10^4
s
andt
consist only of lowercase English letters.
Solutions
Solution 1
Idea: string’s find()
function returns the position of a character when it is found, so I continue to search down from that position, so isn’t that a solution?
We iterate through the string s, searching one by one to see if the character is in the string t. If it is, we add an offset to this position and continue searching for the next character.
|
|
Solution 2
Set double pointers i , j to point to the first character of string s , t respectively, traverse string t :
- When s[i] == t[j], it means the match is successful, then i++ , j++ at the same time; furthermore, if i has gone through the end of s, it means s is a subsequence of t, then it should return true earlier;
- When s[i] ! = t[j], it means the match fails, then only j++ ;
- If after traversing string t, string s is still not traversed, it means s is not a subsequence of t, then return false.
|
|