392. is subsequence


Published: 周二 30 一月 2018

In Leetcode.

我的代码

class Solution:
    def isSubsequence(self, s, t):
        if not s:
            return True
        index = 0
        for c in t:
            if c == s[index]:
                index += 1
                if index == len(s):
                    return True
        return False

最佳方案

速度最快,可能是 find() 时间复杂度比较低,低于 O(n)

class Solution:
    def isSubsequence(self, s, t):
        index = -1
        for c in s:
            index = t.find(c, index + 1)
            if index == -1:
                return False
        return True