{
  "type": "code_options",
  "author": "csdn.net",
  "source": "solution.md",
  "exercise_id": "12ae9e6d8bf1407e9d69b4486405bc26",
  "keywords": "哈希表,字符串,滑动窗口",
  "title": "串联所有单词的子串",
  "desc": [
    {
      "content": "\n<p>给定一个字符串&nbsp;<strong>s&nbsp;</strong>和一些长度相同的单词&nbsp;<strong>words。</strong>找出 <strong>s\n</strong>中恰好可以由&nbsp;<strong>words </strong>中所有单词串联形成的子串的起始位置。</p>\n<p>注意子串要与&nbsp;<strong>words </strong>中的单词完全匹配，中间不能有其他字符，但不需要考虑&nbsp;<strong>words&nbsp;</strong>中单词串联的顺序。</p>\n<p>&nbsp;</p>\n<p><strong>示例 1：</strong></p>\n<pre><strong>输入：  s =</strong> &quot;barfoothefoobarman&quot;,<strong>  words = </strong>[&quot;foo&quot;,&quot;bar&quot;]<strong><br />输出：</strong>[0,9]<strong><br />解释：</strong>从索引 0 和 9 开始的子串分别是 &quot;barfoo&quot; 和 &quot;foobar&quot; 。输出的顺序不重要, [9,0] 也是有效答案。</pre>\n<p><strong>示例 2：</strong></p>\n<pre><strong>输入：  s =</strong> &quot;wordgoodgoodgoodbestword&quot;,<strong>  words = </strong>[&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]<strong><br />输出：</strong>[]</pre>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "java"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "java"
      }
    ],
    [
      {
        "content": "",
        "language": "java"
      }
    ],
    [
      {
        "content": "",
        "language": "java"
      }
    ]
  ],
  "template": {
    "content": "class Solution {\n\tpublic List<Integer> findSubstring(String s, String[] words) {\n\t\tList<Integer> res = new ArrayList<>();\n\t\tif (s == null || s.length() == 0 || words == null || words.length == 0)\n\t\t\treturn res;\n\t\tHashMap<String, Integer> map = new HashMap<>();\n\t\tint one_word = words[0].length();\n\t\tint word_num = words.length;\n\t\tint all_len = one_word * word_num;\n\t\tfor (String word : words) {\n\t\t\tmap.put(word, map.getOrDefault(word, 0) + 1);\n\t\t}\n\t\tfor (int i = 0; i < one_word; i++) {\n\t\t\tint left = i, right = i, count = 0;\n\t\t\tHashMap<String, Integer> tmp_map = new HashMap<>();\n\t\t\twhile (right + one_word <= s.length()) {\n\t\t\t\tString w = s.substring(right, right + one_word);\n\t\t\t\tright += one_word;\n\t\t\t\tif (!map.containsKey(w)) {\n\t\t\t\t\tcount = 0;\n\t\t\t\t\tleft = right;\n\t\t\t\t\ttmp_map.clear();\n\t\t\t\t} else {\n\t\t\t\t\ttmp_map.put(w, tmp_map.getOrDefault(w, 0) + 1);\n\t\t\t\t\tcount++;\n\t\t\t\t\twhile (tmp_map.getOrDefault(w, 0) > map.getOrDefault(w, 0)) {\n\t\t\t\t\t\tString t_w = s.substring(left, left + one_word);\n\t\t\t\t\t\tcount--;\n\t\t\t\t\t\ttmp_map.put(t_w, tmp_map.getOrDefault(t_w, 0) - 1);\n\t\t\t\t\t\tleft += one_word;\n\t\t\t\t\t}\n\t\t\t\t\tif (count == word_num)\n\t\t\t\t\t\tres.add(left);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n}",
    "language": "java"
  },
  "node_id": "dailycode-31ce5d5a421d458cae9da5be0998199a",
  "license": "csdn.net",
  "created_at": 1637894159,
  "topic_link": "https://bbs.csdn.net/topics/600470925"
}