30. Substring with Concatenation of All Words

 avatar
unknown
java
11 days ago
1.6 kB
1
Indexable
public List<Integer> findSubstring(String s, String[] words) {
    List<Integer> result = new ArrayList<>();
    if (s == null || s.length() == 0 || words == null || words.length == 0) return result;

    int wordLen = words[0].length(); // 每個單字的長度
    int wordCount = words.length;
    int totalLen = wordLen * wordCount;

    // 建立 words 出現次數的 Map
    Map<String, Integer> wordCountMap = new HashMap<>();
    for (String word : words) {
        wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
    }

    // 我們總共要做 wordLen 次掃描
    for (int i = 0; i < wordLen; i++) {
        int left = i, right = i;
        Map<String, Integer> seen = new HashMap<>();
        int count = 0;

        while (right + wordLen <= s.length()) {
            String word = s.substring(right, right + wordLen);
            right += wordLen;

            if (wordCountMap.containsKey(word)) {
                seen.put(word, seen.getOrDefault(word, 0) + 1);
                count++;

                // 多了就要從左邊 shrink
                while (seen.get(word) > wordCountMap.get(word)) {
                    String leftWord = s.substring(left, left + wordLen);
                    seen.put(leftWord, seen.get(leftWord) - 1);
                    count--;
                    left += wordLen;
                }

                if (count == wordCount) {
                    result.add(left);
                }
            } else {
                seen.clear();
                count = 0;
                left = right;
            }
        }
    }

    return result;
}
Editor is loading...
Leave a Comment