问题
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:
s = "abc", t = "ahbgdc"
Output:
true
Example 2:
Input:
s = "axc", t = "ahbgdc"
Output:
false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 10
4s
andt
consist only of lowercase English letters.
Follow up: If there are lots of incoming s
, say s
1, s
2, ..., s
k where k >= 10
9, and you want to check one by one to see if t
has its subsequence. In this scenario, how would you change your code?
解答:
从左到右逐个比较主字符串和子字符串
- 相等时,同时移动主串和子字符串索引指向下一个字符
- 不相等,仅移动主串索引指向下一个字符
如果发现子数组的索引已经移动到了数组的末尾,即等于字串长度,表明找到字符串。
class Solution: def isSubsequence(self, s: str, t: str) -> bool: sIdx = 0 tIdx = 0 while sIdx < len(s) and tIdx <len(t): if s[sIdx] == t[tIdx]: sIdx += 1 tIdx += 1 return sIdx == len(s)
参考及引用
Photo by Erik Karits from Pexels
Comments are closed.