30. 串联所有单词的子串

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

  1. 输入:
  2. s = "barfoothefoobarman",
  3. words = ["foo","bar"]
  4. 输出:[0,9]
  5. 解释:
  6. 从索引 0 9 开始的子串分别是 "barfoo" "foobar"
  7. 输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

  1. 输入:
  2. s = "wordgoodgoodgoodbestword",
  3. words = ["word","good","best","word"]
  4. 输出:[]

思路

利用 hash 表。先遍历 words,把每个子串及对应的数量存储到 hash 表中。然后遍历 s,找到符合的开始节点

代码

  1. /*
  2. * @lc app=leetcode.cn id=30 lang=javascript
  3. *
  4. * [30] 串联所有单词的子串
  5. */
  6. // @lc code=start
  7. /**
  8. * @param {string} s
  9. * @param {string[]} words
  10. * @return {number[]}
  11. */
  12. var findSubstring = function (s, words) {
  13. let res = [],
  14. len = words.length;
  15. if (!len) return res;
  16. let hash = new Map(),
  17. itemLen = words[0].length || 0;
  18. // 用hash表存储
  19. for (let cur of words) {
  20. hash[cur] = (hash[cur] || 0) + 1;
  21. }
  22. // console.log(hash);
  23. for (let i = 0; i < s.length - len * itemLen + 1; i++) {
  24. // 复制hash表
  25. let hasHash = {
  26. ...hash,
  27. };
  28. // 获取符合的子串
  29. for (let j = 0; j < words.length; j++) {
  30. const cur = s.substr(i + itemLen * j, itemLen);
  31. if (!hasHash[cur]) {
  32. break;
  33. } else {
  34. hasHash[cur]--;
  35. if (j === words.length - 1) {
  36. res.push(i);
  37. }
  38. }
  39. }
  40. }
  41. return res;
  42. };
  43. // @lc code=end

复杂度分析

时间复杂度 day23.[哈希表].30.串联所有单词的子串 - 图1#card=math&code=O%28N%2AM%29)

空间复杂度 day23.[哈希表].30.串联所有单词的子串 - 图2#card=math&code=O%28M%29)