You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

  1. Input:
  2. s = "barfoothefoobarman",
  3. words = ["foo","bar"]
  4. Output: [0,9]
  5. Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
  6. The output order does not matter, returning [9,0] is fine too.

Example 2:

  1. Input:
  2. s = "wordgoodgoodgoodbestword",
  3. words = ["word","good","best","word"]
  4. Output: []
  

这道题让我们求串联所有单词的子串,就是说给定一个长字符串,再给定几个长度相同的单词,让找出串联给定所有单词的子串的起始位置,还是蛮有难度的一道题。假设 words 数组中有n个单词,每个单词的长度均为 len,那么实际上这道题就让我们出所有长度为 nxlen 的子串,使得其刚好是由 words 数组中的所有单词组成。那么就需要经常判断s串中长度为 len 的子串是否是 words 中的单词,为了快速的判断,可以使用 HashMap,同时由于 words 数组可能有重复单词,就要用 HashMap 来建立所有的单词和其出现次数之间的映射,即统计每个单词出现的次数。

遍历s中所有长度为 nxlen 的子串,当剩余子串的长度小于 nxlen 时,就不用再判断了。所以i从0开始,到 (int)s.size() - nxlen 结束就可以了,注意这里一定要将 s.size() 先转为整型数,再进行解法。一定要形成这样的习惯,一旦 size() 后面要减去数字时,先转为 int 型,因为 size() 的返回值是无符号型,一旦减去一个比自己大的数字,则会出错。对于每个遍历到的长度为 nxlen 的子串,需要验证其是否刚好由 words 中所有的单词构成,检查方法就是每次取长度为 len 的子串,看其是否是 words 中的单词。为了方便比较,建立另一个 HashMap,当取出的单词不在 words 中,直接 break 掉,否则就将其在新的 HashMap 中的映射值加1,还要检测若其映射值超过原 HashMap 中的映射值,也 break 掉,因为就算当前单词在 words 中,但若其出现的次数超过 words 中的次数,还是不合题意的。在 for 循环外面,若j正好等于n,说明检测的n个长度为 len 的子串都是 words 中的单词,并且刚好构成了 words,则将当前位置i加入结果 res 即可,具体参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. vector<int> findSubstring(string s, vector<string>& words) {
  4. if (s.empty() || words.empty()) return {};
  5. vector<int> res;
  6. int n = words.size(), len = words[].size();
  7. unordered_map<string, int> wordCnt;
  8. for (auto &word : words) ++wordCnt[word];
  9. for (int i = ; i <= (int)s.size() - n * len; ++i) {
  10. unordered_map<string, int> strCnt;
  11. int j = ;
  12. for (j = ; j < n; ++j) {
  13. string t = s.substr(i + j * len, len);
  14. if (!wordCnt.count(t)) break;
  15. ++strCnt[t];
  16. if (strCnt[t] > wordCnt[t]) break;
  17. }
  18. if (j == n) res.push_back(i);
  19. }
  20. return res;
  21. }
  22. };

这道题还有一种 O(n) 时间复杂度的解法,设计思路非常巧妙,但是感觉很难想出来,博主目测还未到达这种水平。这种方法不再是一个字符一个字符的遍历,而是一个词一个词的遍历,比如根据题目中的例子,字符串s的长度n为 18,words 数组中有两个单词 (cnt=2),每个单词的长度 len 均为3,那么遍历的顺序为 0,3,6,8,12,15,然后偏移一个字符 1,4,7,9,13,16,然后再偏移一个字符 2,5,8,10,14,17,这样就可以把所有情况都遍历到,还是先用一个 HashMap m1 来记录 words 里的所有词,然后从0开始遍历,用 left 来记录左边界的位置,count 表示当前已经匹配的单词的个数。然后一个单词一个单词的遍历,如果当前遍历的到的单词t在 m1 中存在,那么将其加入另一个 HashMap m2 中,如果在 m2 中个数小于等于 m1 中的个数,那么 count 自增1,如果大于了,则需要做一些处理,比如下面这种情况:s = barfoofoo, words = {bar, foo, abc},给 words 中新加了一个 abc ,目的是为了遍历到 barfoo 不会停止,当遍历到第二 foo 的时候,  m2[foo]=2, 而此时 m1[foo]=1,这时候已经不连续了,所以要移动左边界 left 的位置,先把第一个词 t1=bar 取出来,然后将 m2[t1] 自减1,如果此时 m2[t1]<m1[t1] 了,说明一个匹配没了,那么对应的 count 也要自减1,然后左边界加上个 len,这样就可以了。如果某个时刻 count 和 cnt 相等了,说明成功匹配了一个位置,将当前左边界 left 存入结果 res 中,此时去掉最左边的一个词,同时 count 自减1,左边界右移 len,继续匹配。如果匹配到一个不在 m1 中的词,说明跟前面已经断开了,重置 m2,count 为0,左边界 left 移到 j+len,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. vector<int> findSubstring(string s, vector<string>& words) {
  4. if (s.empty() || words.empty()) return {};
  5. vector<int> res;
  6. int n = s.size(), cnt = words.size(), len = words[].size();
  7. unordered_map<string, int> m1;
  8. for (string w : words) ++m1[w];
  9. for (int i = ; i < len; ++i) {
  10. int left = i, count = ;
  11. unordered_map<string, int> m2;
  12. for (int j = i; j <= n - len; j += len) {
  13. string t = s.substr(j, len);
  14. if (m1.count(t)) {
  15. ++m2[t];
  16. if (m2[t] <= m1[t]) {
  17. ++count;
  18. } else {
  19. while (m2[t] > m1[t]) {
  20. string t1 = s.substr(left, len);
  21. --m2[t1];
  22. if (m2[t1] < m1[t1]) --count;
  23. left += len;
  24. }
  25. }
  26. if (count == cnt) {
  27. res.push_back(left);
  28. --m2[s.substr(left, len)];
  29. --count;
  30. left += len;
  31. }
  32. } else {
  33. m2.clear();
  34. count = ;
  35. left = j + len;
  36. }
  37. }
  38. }
  39. return res;
  40. }
  41. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/30

类似题目:

Minimum Window Substring

参考资料:

https://leetcode.com/problems/substring-with-concatenation-of-all-words/

https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/13656/An-O(N)-solution-with-detailed-explanation

https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/13658/Easy-Two-Map-Solution-(C%2B%2BJava)

https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/13664/Simple-Java-Solution-with-Two-Pointers-and-Map

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 30. Substring with Concatenation of All Words 串联所有单词的子串的更多相关文章

  1. [LeetCode] Substring with Concatenation of All Words 串联所有单词的子串

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

  2. [leetcode]30. Substring with Concatenation of All Words由所有单词连成的子串

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

  3. LeetCode 30 Substring with Concatenation of All Words(确定包含所有子串的起始下标)

    题目链接: https://leetcode.com/problems/substring-with-concatenation-of-all-words/?tab=Description   在字符 ...

  4. LeetCode - 30. Substring with Concatenation of All Words

    30. Substring with Concatenation of All Words Problem's Link --------------------------------------- ...

  5. [LeetCode] 30. Substring with Concatenation of All Words 解题思路 - Java

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

  6. leetCode 30.Substring with Concatenation of All Words (words中全部子串相连) 解题思路和方法

    Substring with Concatenation of All Words You are given a string, s, and a list of words, words, tha ...

  7. [LeetCode] 30. Substring with Concatenation of All Words ☆☆☆

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

  8. Java [leetcode 30]Substring with Concatenation of All Words

    题目描述: You are given a string, s, and a list of words, words, that are all of the same length. Find a ...

  9. LeetCode HashTable 30 Substring with Concatenation of All Words

    You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...

随机推荐

  1. 一段完整的创建表格的SQL代码

    一段完整的创建表格的SQL代码 使用SQL语句创建一张表,不仅可以可以快速熟悉SQL语句,还可以从这看出一个人对该技能点的熟悉程度. 这里先说明几点: PRIMARY KEY:主键,一张表中只允许有一 ...

  2. vue中toggle切换的3种写法

    前言:查看下面代码,在任意编辑器中直接复制粘贴运行即可 1:非动态组件(全局注册2个组件,借用v-if指令和三元表达式) <!DOCTYPE html> <html> < ...

  3. python Condition

    import threading # 必须要使用condition的例子 # class XiaoAi(threading.Thread):# def __init__(self, lock):# s ...

  4. Spring Boot整合Mybatis配置详解

    首先,你得有个Spring Boot项目. 平时开发常用的repository包在mybatis里被替换成了mapper. 配置: 1.引入依赖: <dependency> <gro ...

  5. 云原生生态周报 Vol. 12 | K8s 1.16 API 重大变更

    本文作者:源三.临石.张磊.莫源 业界要闻 1. K8s 1.16 将废弃一系列旧的 API 版本 影响面涉及 NetworkPolicy.PodSecurityPolicy.DaemonSet, D ...

  6. Grafana的Docker部署方式

    docker run -d -p : --name=grafana544 -v D:/grafana/grafana-/data:/var/lib/grafana -v D:/grafana/graf ...

  7. ASP.NET MVC 中的过滤器

    这里用实例说明各种过滤器的用法,有不对的地方还请大神指出,共同探讨. 1. ActionFilter 方法过滤器: 接口名为 IActionFilter ,在控制器方法调用前/后执行. 在新建的MVC ...

  8. hashmap与hashtable的本质区别

    HashMap 底层数据结构是哈希表.线程不安全,效率高                哈希表依赖两个方法:hashCode()和equals()                执行顺序:       ...

  9. selenium鼠标操作 包含右击和浮层菜单的选择

    感谢http://www.cnblogs.com/tobecrazy/p/3969390.html  博友的分享 最近在学习selenium的一些鼠标的相关操作 自己在百度的相关操作代码 /** * ...

  10. PHP初探--wamp安装配置

    WAMP = Windows下的 Apache + MySQL+PHP WampServer的安装与配置 直接百度,下载后直接跟着安装步骤走就OK. 安装成功后,点击运行,然后电脑右下角会出现图标.服 ...