392. 判断子序列
"""
392. 判断子序列
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
进阶:
如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
致谢:
特别感谢 @pbrother 添加此问题并且创建所有测试用例。
示例 1:
输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:
输入:s = "axc", t = "ahbgdc"
输出:false
提示:
0 <= s.length <= 100
0 <= t.length <= 10^4
两个字符串都只由小写字符组成。
"""
class Solution(object):
#这个需要不考虑字符串的顺序
def isSubsequence1(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s == "": return True
need, window = {}, {}
count = 0
for i in s:
need[i] = need.get(i, 0) + 1
for i in t:
if i in need:
window[i] = window.get(i, 0) + 1
if window[i] == need[i]:
count += 1
if count == len(need):
return True
return False
#基于递归方式
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if not s: return True
if not t: return False
if s[0] == t[0]:
return self.isSubsequence(s[1:], t[1:])
else:
return self.isSubsequence(s, t[1:])
if __name__ == "__main__":
s = ""
t = "ahbgdc"
res = Solution().isSubsequence(s,t)
print(res)
posted on 2021-12-15 09:46 random_boy 阅读(33) 评论(0) 收藏 举报
浙公网安备 33010602011771号