【leetcode】392. 判断子序列
文章目录
- 题目
- 题解
- 1. 双循环
- 2. 双指针
- 3. 动态规划
题目
392. 判断子序列
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
进阶:
如果有大量输入的 S,称作 S1, S2, … , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
示例 1:
输入:s = “abc”, t = “ahbgdc”
输出:true
示例 2:
输入:s = “axc”, t = “ahbgdc”
输出:false
题解
1. 双循环
class Solution(object):def isSubsequence(self, s, t):""":type s: str:type t: str:rtype: bool"""slow = 0fast = 0w = 0if len(s) == 0:return Trueif len(t) == 0:return Falsefor i in range(len(s)):if w >= len(t):return Falsefor j in range(w, len(t)):if j < len(t) and t[j] == s[i]:w = j + 1if i == len(s) - 1:return Truebreakelif j < len(t) - 1 and t[j] != s[i]:continueelif j == len(t) - 1 and t[j] != s[i]:return Falsereturn True
2. 双指针
class Solution(object):def isSubsequence(self, s, t):""":type s: str:type t: str:rtype: bool"""n, m = len(s), len(t)i = j = 0while i < n and j < m:if s[i] == t[j]:i += 1j += 1else:j += 1return i == n
3. 动态规划
class Solution(object):def isSubsequence(self, s, t):""":type s: str:type t: str:rtype: bool"""n, m = len(s), len(t)i = j = 0while i < n and j < m:if s[i] == t[j]:i += 1j += 1else:j += 1return i == n
代码随想录