题目描述

https://leetcode-cn.com/problems/minimum-window-substring/

解题思路

image.png

  • 先找出所有包含T所有字符的子串
  • 返回长度最小的子串

解题步骤

  • 用双指针维护一个滑动窗口
  • 移动右指针,找到包含T所有字符的子串,移动左指针,尽量减少包含T的子串的长度
  • 循环上述过程,找出包含T所有字符的最小子串

代码实现

  1. /**
  2. * @param {string} s
  3. * @param {string} t
  4. * @return {string}
  5. */
  6. var minWindow = function (s, t) {
  7. let l = 0
  8. let r = 0
  9. const need = new Map() // 字典,用以表示需要的字符以及它的个数
  10. for (let c of t) {
  11. need.set(c, need.has(c) ? need.get(c) + 1 : 1)
  12. }
  13. console.log(need) // 罗列出t的所有字符和个数
  14. let needNum = need.size
  15. let result = ''
  16. while (r < s.length) {
  17. const c = s[r]
  18. if (need.has(c)) {
  19. need.set(c, need.get(c) - 1)
  20. if (need.get(c) === 0) needNum--
  21. }
  22. while (needNum === 0) { // 当子串包含t中所有字符时b
  23. // console.log(s.substring(l, r + 1)) // 所有满足条件的子串
  24. const newResult = s.substring(l, r + 1)
  25. if (!result || newResult.length < result.length) result = newResult
  26. const c2 = s[l]
  27. if (need.has(c2)) {
  28. need.set(c2, need.get(c2) + 1)
  29. if (need.get(c2) === 1) needNum++
  30. }
  31. l++
  32. }
  33. r++
  34. }
  35. return result
  36. };

时间复杂度: O(n+m) m是t的长度,n是s的长度
空间复杂度: O(k) k是t里面不同字符的个数