问题描述:
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
输入: s1 = “ab” s2 = “eidbaooo”
输出: True
解释: s2 包含 s1 的排列之一 (“ba”).
输入: s1= “ab” s2 = “eidboaoo”
输出: False
注意:
- 输入的字符串只包含小写字母
- 两个字符串的长度都在 [1, 10,000] 之间
解决方法:
# 基本思路是 比较 s1中的每个字母在 s2的子串中出现的次数
# s2的子串长度 等于 s1 的长度
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
s1_len = len(s1)
s2_len = len(s2)
start_index = 0
end_index = start_index + s1_len
element_hash = {}
for element in s1:
if element not in element_hash.keys():
element_hash[element] = 1
else:
element_hash[element] +=1
print element_hash
while end_index <= s2_len:
split_str = s2[start_index : end_index]
for character_type, character_count in element_hash.items():
if character_type not in split_str:
break
elif character_count != split_str.count(character_type):
break
else:
return True
start_index += 1
end_index += 1
return False