Leetcode-talk26判断子序列

给定字符串 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.

思路一:库函数

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool: 
        loc = -1
        for a in s:
            loc = t.find(a, loc + 1)
            if loc == -1:
                return False
        return True

思路二:生成迭代器

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        t = iter(t)
        return all(c in t for c in s)

思路三:双指针

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i = 0
        j = 0
        while i < len(s) and j < len(t):
            # print(i, j)
            if s[i] == t[j]:
                i += 1
                j += 1
            else:
                j += 1    
        return i == len(s)
发布了41 篇原创文章 · 获赞 0 · 访问量 488

猜你喜欢

转载自blog.csdn.net/qq_39199884/article/details/105122123