leetcode 392 判断s是否是t的子序列

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        # s is much smaller than t

        i, j =0, 0
        while i <= len(s)-1 and j<= len(t)-1:
            if s[i] == t[j]:
                i+=1
                j+=1
            else:
                j+=1
        if i==len(s) :
            return True
        else:
            return False

很奇妙的解,双指针遍历 i ,j
如果两个指针所指元素相等,指针同时后移动。
如果不相等, t的指针+1,直到两个指针溢出。
最后判断字符串s的指针是否等于s的长度,相等则说明True.

a,b,c
a,e,b, d,d,c

b,c
e, b d,d,c

b,c
b,d,d,c

c
d,d,c

c
d,c

c
c

i == len(s)
return True

猜你喜欢

转载自blog.csdn.net/weixin_43702920/article/details/107092289