力扣的判断子序列 解法(Python3)

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

力扣的判断子序列 解法

题目描述:

给定字符串 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:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值