描述

滑动窗口-字符串排列 - 图1

  • input S: ‘helloworld’ T: ‘dlr’
  • output True or False
  1. def checkInclusion(S: str, T: str) -> bool:
  2. need: dict[str:int] = {}
  3. window: dict[str:int] = {}
  4. flag: int = 0
  5. for c in T:
  6. need[c] = need.get(c, 0) + 1
  7. left: int = 0
  8. right: int = 0
  9. while right < len(S):
  10. c: str = S[right]
  11. right += 1
  12. if c in T:
  13. window[c] = window.get(c, 0) + 1
  14. if window[c] == need[c]:
  15. flag += 1
  16. # 当flag满足条件时候, 目标串可能出现
  17. while flag == len(need):
  18. if right - left == len(T): # [left, right], 这是当前窗口状态
  19. return True
  20. c = S[left]
  21. if c in T:
  22. if window[c] == need[c]:
  23. flag -= 1
  24. window[c] -= 1
  25. left += 1
  26. return False
  27. print(checkInclusion('w321ww', '231'))