392. Is Subsequence

问题

给定两个字符串,s 和 t,判断s是不是t的一个子序列

s = "abc", t = "ahbgdc"
Return true
s = "axc", t = "ahbgdc"
Return false.

思路

两个指针移动,如果相等s和t都移动一步,不相等则t移动一步,最后如果s移动到最后,则说明s是t的一个子序列。

时间复杂度O(n),空间复杂度O(1)

代码

class Solution(object):
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if(s==''):
            return True
        if(t==''):
            return False
        i = 0
        j = 0
        while j<len(t) and i<len(s):
            if(t[j] == s[i]):
                i += 1
            j += 1
        return i == len(s)    

类似题目

115. Distinct Subsequences

posted @ 2018-10-11 08:50  PilgrimHui  阅读(324)  评论(0编辑  收藏  举报