leetcode 392.判断子序列
题目大意:
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
思路:运用双指针的思想,给s和t分别设置指针i,j,循环中让j一直递增,来寻找t串中是否有s[i]元素。如果t[j] == s[i]即s[i]被匹配到了那么i,j,ans都加1,继续向后匹配。最终若ans等于s串的长度,则匹配成功。
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
ans, i, j = 0, 0, 0
l1, l2 = len(s), len(t)
while i<l1 and j<l2:
if s[i] == t[j]:
i = i + 1
ans = ans + 1
j = j + 1
if ans == l1:
return True
else:
return False
思考为什么用双指针,因为这里的匹配要考虑t串中字符的相对顺序,即"ab"不是"bca"的子串。如果直接for,就会出现顺序错误的匹配问题。
附一段通过测试点14/15的代码,思路一样,但就是不知道为什么错了……
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if s == t:
return True
ans = 0
j = 0
temp = ""
for item in t:
if item in s:
temp = temp + item
for i in range(len(s)):
while j <= len(temp)-1:
if temp[j] == s[i]:
j += 1
ans += 1
break
else:
j += 1
if ans == len(s):
return True
else:
return False