Q:
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo" 输出: True 解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo" 输出: False
注意:
- 输入的字符串只包含小写字母
- 两个字符串的长度都在 [1, 10,000] 之间
思路:
首先使用双指针,也就是设置一个滑动窗口,判断与len(s1)长度大小相符的窗口内的字符串是否能够匹配,匹配的方式就是设置一个长度为26的temp list在s1中有的字符就+1 在s2[slow:fast]中的字符就-1 看最后能否为全0,但是超时
【超时】
class Solution:
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s1) > len(s2):
return False
if s1 in s2:
return True
temp = [s for s in s1]
slow = 0
fast = 1
while (fast <= len(s2)):
if s2[slow] in temp:
fast = slow+len(s1)
temp1 = [0 for _ in range(26)]
if self.check(s1,s2[slow:fast],temp1):
return True
else:
slow+=1
fast = slow + len(s1)
else:
slow+=1
fast = slow + len(s1)
return False
def check(self,s1_,s2_,temp1):
for i in range(len(s1_)):
temp1[ord(s1_[i])-ord('a')]+=1
temp1[ord(s2_[i])-ord('a')]-=1
if temp1.count(0) == 26:
return True
else:
return False
参考了一下别人的代码,更改遍历方式:
class Solution:
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
def match(self, s1, s2):
return s1 == s2
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if len(s1) > len(s2):
return False
list1 = [0 for i in range(26)]
list2 = [0 for i in range(26)]
for i in range(len(s1)):
list1[ord(s1[i]) - ord('a')] += 1
list2[ord(s2[i]) - ord('a')] += 1
for i in range(len(s2) - len(s1)):
if self.match(list1, list2):
return True
list2[ord(s2[i + len(s1)]) - ord('a')] += 1
list2[ord(s2[i]) - ord('a')] -= 1
return self.match(list1, list2)
用时最少的代码,思路基本是一样的其实:
class Solution:
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
cnt1 = [0]*26;
cnt2 = [0]*26;
for c in s1:
cnt1[ord(c)-ord('a')]+=1
for i in range(len(s2)):
cnt2[ord(s2[i])-ord('a')]+=1
if i<len(s1)-1:
continue
if cnt2==cnt1:
return True
cnt2[ord(s2[i-len(s1)+1])-ord('a')] -=1
return False