判断子序列392

题目:给定字符串 st ,判断 s 是否为 t 的子序列。

你可以认为 st 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde"的一个子序列,而"aec"不是)。

输入:s = "abc", t = "ahbgdc"

输出:True

思路:贪心算法,对于s中的每个元素进行查找,如果不在t中,返回False,否则查找其在t中的第一个位置,更新t为此位置后面的元素

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class :
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""

if not s:
return True
if not t:
return False
# 对于s中的每个字符判断其是否在t中
for sub_s in s:
if sub_s not in t:
return False
# 更新t
t = t[t.index(sub_s)+1:]
return True
# 例子
s = 'axc'
t = 'ahbgdc'
print(Solution().isSubsequence(s,t))