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

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

例如:

  • 输入:

s = "barfoothefoobarman", words = ["foo","bar"]

  • 输出:

[0,9]

  • 解释:

从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" ,输出的顺序不重要, [9,0] 也是有效答案!

//串联所有单词的子串


//两个hashmap解决问题
public List<Integer> findSubstring(String s, String[] words) {
    List<Integer> res = new ArrayList<Integer>();

    //字符串数组长度
    int wordNum = words.length;
    if (wordNum == 0) {
        return res;
    }

    //第一个单词的长度
    int wordLen = words[0].length();
    //allWors存放所有单词,key存放单词,value存放单词出现的个数
    HashMap<String, Integer> allWords = new HashMap<String, Integer>();

    for (String w : words) {
        int value = allWords.getOrDefault(w, 0);
        allWords.put(w, value + 1);
    }

    //遍历所有字符
    for (int i = 0; i < s.length() - wordNum * wordLen + 1; i++) {
        //存在扫描字符串中含有的单词        
        HashMap<String, Integer> hasWords = new HashMap<String, Integer>();
        int num = 0;
        
        while (num < wordNum) {
            //取的字符串长度是wordLen
            String word = s.substring(i + num * wordLen, i + (num + 1) * wordLen);
           
            if (allWords.containsKey(word)) {
                //如果单词存在,存放在hasWors中
                int value = hasWords.getOrDefault(word, 0);
                hasWords.put(word, value + 1);
                
                if (hasWords.get(word) > allWords.get(word)) {
                    //大于则不是我们要找的
                    break;
                }
            } else {
                break;
            }
            num++;
        }
        
        if (num == wordNum) {
            res.add(i);
        }
    }

    return res;
}

链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-6/