[LeetCode] 392. 判断子序列

34 阅读1分钟

392. 判断子序列

Easy

思路

  • 使用双指针方式,一个指针i指向s的开头,另一个指向t的开头
  • 第二个指针遍历t,当遇到s[i]与当前元素相同时,i向后移动一位
  • i移动完了之后,说明匹配成功,否则匹配失败
  • 特判:当s == ""返回True

以上,AC!

代码

python3

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
      if s is "":
        return True
      i = 0
      for l in t:
        if s[i] == l:
          i += 1
          if i >= len(s):
            return True
      return False