Leetcode刷题(第76题)——最小覆盖子串

x33g5p2x  于2022-03-05 转载在 其他  
字(1.0k)|赞(0)|评价(0)|浏览(280)

一、题目

  1. 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""
  2. 注意:
  3. 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。如果 s 中存在这样的子串,我们保证它是唯一的答案。

二、示例

  1. 示例一:
  2. 输入:s = "ADOBECODEBANC", t = "ABC"
  3. 输出:"BANC"
  4. 示例二
  5. 输入:s = "a", t = "a"
  6. 输出:"a"

三、解题思路

  1. 这题维护一个移动滑块,首先先移动右滑块保证字符串t中可以全部覆盖
  2. 然后不断的移动左滑块,当不满足条件时,然后再去移动右滑块。

四、代码展示

  1. /**
  2. * @param {string} s
  3. * @param {string} t
  4. * @return {string}
  5. */
  6. var minWindow = function (s, t) {
  7. let map = new Map()
  8. let needType = 0
  9. for (let i = 0; i < t.length; i++) {
  10. if (map.has(t[i])) {
  11. map.set(t[i], map.get(t[i]) + 1)
  12. } else {
  13. map.set(t[i], 1)
  14. needType += 1
  15. }
  16. }
  17. let left = 0;
  18. let right = 0;
  19. let res = ""
  20. while (right < s.length) {
  21. let curR = s[right]
  22. if (map.has(curR)) {
  23. map.set(curR, map.get(curR) - 1)
  24. if (map.get(curR) === 0) {
  25. needType -= 1
  26. }
  27. }
  28. while (needType === 0) {
  29. let curStr = s.substr(left, right - left + 1)
  30. let curL = s[left]
  31. if (!res || res.length > curStr.length) {
  32. res = curStr
  33. }
  34. if (map.has(curL)) {
  35. map.set(curL, map.get(curL) + 1)
  36. if(map.get(curL) === 1) {
  37. needType += 1
  38. }
  39. }
  40. left++
  41. }
  42. right++
  43. }
  44. return res
  45. };

五、总结

相关文章