思路:
所谓异位词,就是和原来的词在数量和字母类型上一致。可以用字典判断。
虽然滑动窗口可以做,但是双指针保证扫描一遍,保持窗口大小是目标词大小。真香!
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
def str_2_dict(s):
s_dict = {}
for c in s:
s_dict[c] = s_dict.get(c, 0) + 1
return s_dict
left = 0
right = len(p)
ans = []
windows = s[left:right]
while right <= len(s):
windows = s[left:right]
# print(windows)
if str_2_dict(windows) == str_2_dict(p):
ans.append(left)
left += 1
right += 1
return ans
字符串转换成字典比较太慢了,时间超了!!
def str_2_dict(s):
s_dict = {}
for c in s:
s_dict[c] = s_dict.get(c, 0) + 1
return s_dict
用26位的数组表示26个字母,相应索引下的数字表示出现的次数!!
alph_hash = [0]*26
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
def alph_hash(s):
table = [0]*26
for c in s:
table[ord(c)-97] += 1
return table
left = 0
right = len(p)-1
target = alph_hash(p)
ans = []
windows = s[left:right+1]
hash_windows = alph_hash(windows)
while right < len(s):
if hash_windows == target:
ans.append(left)
hash_windows[ord(s[left])-97] -= 1
# 计算下一个hahs_windows
left += 1
right += 1
if right >= len(s):
break
hash_windows[ord(s[right])-97] += 1
print(hash_windows)
return ans