LeetCode 392. 判断子序列

时间:2022-07-22
本文章向大家介绍LeetCode 392. 判断子序列,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目

给定字符串 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 的子序列。在这种情况下,你会怎样改变代码?

解题思路

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        # #双指针
        # sList = list(s)
        # tList = list(t)
        # if len(sList) <= 0:return True
        # if len(tList) <= 0:return False
        # sIndex = 0
        # # tIndex = 0
        # for i in tList:
        #     if i == sList[sIndex]:
        #         sIndex = sIndex + 1
        #         if sIndex == len(s):
        #             return True
        # return False
        #动态规划,对t进行预处理,形成一个二维数组,记录每个字母的下一个位置
        # t = " "+t
        sLen, tLen = len(s), len(t)
        #预处理
        dp = [[-1]*26 for _ in range(tLen+1)]
        # dp.append([-1]*26)
        for i in range(tLen-1,-1,-1):
            ordChar = ord(t[i]) - 97
            for j in range(26):
                dp[i][j] = i if j == ordChar else dp[i+1][j]
        print(dp)
        #进行搜索定位
        nextIndex = 0
        for j in s:
            ordChar = ord(j) - 97
            if dp[nextIndex][ordChar] == -1:return False
            nextIndex = dp[nextIndex][ordChar] + 1
            print("ord:{} nextindex:{}".format(ordChar, nextIndex))
        return True