题目
    438.找到字符串中所有字母异位词

    思路
    image.png
    所谓异位词,就是和原来的词在数量和字母类型上一致。可以用字典判断。
    虽然滑动窗口可以做,但是双指针保证扫描一遍,保持窗口大小是目标词大小。真香!

    1. class Solution:
    2. def findAnagrams(self, s: str, p: str) -> List[int]:
    3. def str_2_dict(s):
    4. s_dict = {}
    5. for c in s:
    6. s_dict[c] = s_dict.get(c, 0) + 1
    7. return s_dict
    8. left = 0
    9. right = len(p)
    10. ans = []
    11. windows = s[left:right]
    12. while right <= len(s):
    13. windows = s[left:right]
    14. # print(windows)
    15. if str_2_dict(windows) == str_2_dict(p):
    16. ans.append(left)
    17. left += 1
    18. right += 1
    19. return ans

    字符串转换成字典比较太慢了,时间超了!!

    1. def str_2_dict(s):
    2. s_dict = {}
    3. for c in s:
    4. s_dict[c] = s_dict.get(c, 0) + 1
    5. return s_dict

    用26位的数组表示26个字母,相应索引下的数字表示出现的次数!!

    1. alph_hash = [0]*26
    1. class Solution:
    2. def findAnagrams(self, s: str, p: str) -> List[int]:
    3. def alph_hash(s):
    4. table = [0]*26
    5. for c in s:
    6. table[ord(c)-97] += 1
    7. return table
    8. left = 0
    9. right = len(p)-1
    10. target = alph_hash(p)
    11. ans = []
    12. windows = s[left:right+1]
    13. hash_windows = alph_hash(windows)
    14. while right < len(s):
    15. if hash_windows == target:
    16. ans.append(left)
    17. hash_windows[ord(s[left])-97] -= 1
    18. # 计算下一个hahs_windows
    19. left += 1
    20. right += 1
    21. if right >= len(s):
    22. break
    23. hash_windows[ord(s[right])-97] += 1
    24. print(hash_windows)
    25. return ans