力扣的判断子序列 解法
题目描述:
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = “abc”, t = “ahbgdc”
返回 true.
示例 2:
s = “axc”, t = “ahbgdc”
返回 false.
后续挑战 :
如果有大量输入的 S,称作S1, S2, … , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/regular-expression-matching
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考程序1:
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not t and not s:
return True
ls = list(s)
temp_index = -1
index = 0
for i in ls:
index = t.find(i)
t = t[index+1:]
index += temp_index + 1
if index <= temp_index:
return False
temp_index = index
return True
运行结果1:

参考程序2:
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
ls=len(s)
xl=0
for j in t:
if xl==ls:
return True
if j==s[xl]:
xl+=1
return xl==ls
运行结果2:

参考程序3:
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
result, temp = 0, 0
while result < len(s) and temp < len(t):
if s[result] == t[temp]:
result += 1
temp += 1
return result == len(s)
运行结果3:

本文介绍了解决力扣(LeetCode)中判断子序列问题的三种不同方法。问题要求判断字符串s是否为字符串t的子序列,适用于s长度小于等于100,而t可能长达500,000的情况。提供了使用find方法、遍历比较和双指针技术的解决方案。
188

被折叠的 条评论
为什么被折叠?



