问题
Given two strings s and t, check if s is a subsequence of t.
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:
Input:
| |
Output:
| |
Example 2:
Input:
| |
Output:
| |
Constraints:
0 <= s.length <= 1000 <= t.length <= 104sandtconsist only of lowercase English letters.
Follow up: If there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
解答:
从左到右逐个比较主字符串和子字符串
- 相等时,同时移动主串和子字符串索引指向下一个字符
- 不相等,仅移动主串索引指向下一个字符
如果发现子数组的索引已经移动到了数组的末尾,即等于字串长度,表明找到字符串。
| |
参考及引用
Photo by Erik Karits from Pexels