数据结构之判断子序列

(leetcode刷题)

判断子序列

  题目: 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。
  示例: s = "abc", t = "ahbgdc";返回 true.
 

方法:递归

  • 挨个找子字符串中的字符,找到就递归下一个,找不到就返回False
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        if not t:return not s
        if not s:return True
        for each in s:
            if each in t:
                index=t.find(each)
                return self.isSubsequence(s[1:],t[index+1:])
            else:
                return False

在这里插入图片描述

发布了60 篇原创文章 · 获赞 2 · 访问量 1459

猜你喜欢

转载自blog.csdn.net/qq_40160983/article/details/105093966