Day9-Is Subsequence Solution(easy)
问题描述:
Given a string s and a string t, check if s is subsequence of t.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).
Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
判断一个字符串是否是模板字符串的子字符串,所谓子字符串就是字符串中所有字符都在模板字符串中出现过,并且先后顺序一致。
Example:
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 10^4
Both strings consists only of lowercase characters.
解法:
这么简单的一道题,我竟然没想到。。。深深为自己的脑力担忧啊,越练越回去了怎么。。
就是设置两个指针分别从s,t的头部遍历,如果两者相同,则指针同时向后移动一位,否则t的指针向后移动,直到两者中有一个遍历到最后为止,最后看一下s的指针是否等于s的长度就可以了。时间复杂度为O(N)
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i , j = 0,0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
else:
j += 1
return i == len(s)
解法二(针对follow up):
针对follow up中所提到的多个s进行判断时的考虑,我们可以将模板t固定住,通过一个hash表建立t中字符和对应位置的映射,对于重复的字符,可以用一个列表存储重复数字出现的位置。然后我们遍历s这样对于一个字符先判断是否出现在字典中,在找到字典中出现该字符的位置,由于对应位置要求不能改变顺序,我们可以设置一个变量存储当前字符的位置,如果后续遍历的字符的位置小于当前位置则直接False,对于重复数字,我们要在其对应的位置列表中找到第一个大于当前位置变量的值,更新当前位置变量。这个寻找的过程,我们可以用二分搜索法降低时间复杂度,我下面的代码并没有使用。
这种解法似乎增大了时间复杂度和空间复杂度,我也没太明白为什么多个S后要用这种解法,但是看了discuss和其他大神的博客都说的是要这么解,虽然我一开始做这道题也想的是用字典存位置这种做法,中间没想到用变量存当前位置这一步所以刚开始没写出来,但是看了大神的博客后发现还是解法一香。
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
t_dict = collections.defaultdict(list)
pre = -1
for i in range(len(t)):
t_dict[t[i]].append(i)
for i in range(len(s)):
if s[i] in t_dict:
#如果在这个列表中,要找到这个列表中刚好大于pre的值,如果没有则返回false
j = 0
while j < len(t_dict[s[i]]):
if t_dict[s[i]][j] > pre:
pre = t_dict[s[i]][j]
break
else:
j += 1
if j == len(t_dict[s[i]]):
return False
else:
return False
return True