392. Is Subsequence -Medium

Question

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

给出两个字符串s, t,判断s是否是t的子集。t大约有500000个字符, s不超过100个字符。这里的子集的判断是允许删除一些中间的字符得到的剩余字符相同(也就是不需要连续相同的字符串)

Example

s = “abc”, t = “ahbgdc”

Return true.


s = “axc”, t = “ahbgdc”

Return false.

Solution

  • 这道题还是比较简单的,如果s是t的子集,那么s中的所有字符必然按照相同的顺序出现在t中,所以我们可以分别建立两个字符串的索引,每当t中出现s的当前字符,就搜索s的下一个字符,直到s的所有字符均在t中找到

    class Solution(object):
        def isSubsequence(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            # 如果s是空字符串,那么它是任意字符串的子集
            if len(s) == 0: return True
    
            index_s, index_t = 0, 0
            # 遍历t
            for current_t in t:
                # 如果s的当前元素被找到,则继续寻找下一个s
                if s[index_s] == current_t:
                    index_s += 1
                    # 如果s的所有字符都被找到,代表s是t的子集
                    if index_s == len(s): return True
            # 如果搜索完t仍然没有找全s,代表s不是t的子集
            return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值