Статья пока доступна только на английском.
Problem Description
You are given two strings s and t.
Write a function that returns true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string formed from the original one by deleting some (possibly none)
characters without changing the relative positions of the remaining characters (i.e. ace is a subsequence
of abcde, while aec is not).
Constraints
- The length of
sis in the range from 0 to 100 - The length of
tis in the range from 0 to 10000 - Both strings consist only of lowercase English letters
Examples
Input: s = "abc", t = "ahbgdc"
Answer: true
Solution
We'll use the simplest approach: walking through both strings with two pointers.
We loop over all characters of t and compare them with the characters of s.
To track our position in s, we use the pointer pos.
- If the characters match, we move
posone position forward. - If after going through all characters of
tthe pointerpospoints to the end ofs, thensis a subsequence oft. - If this condition becomes true during some iteration, we can exit early and return
true, since there is no point in scanning the rest oft.
export const isSubsequence = (s: string, t: string): boolean => {
let pos = 0;
if (s === '') {
return true;
}
for (let i = 0; i < t.length; i++) {
const char = t[i];
if (pos === s.length) {
return true;
}
if (char === s[pos]) {
pos++;
}
}
return pos === s.length;
};Complexity Analysis
Time Complexity
O(n), where n is the length of t.
Space Complexity
O(1), since we use a constant amount of memory for variables.