package com.hong.www; import java.util.*; class A30_2 { public List findSubstring(String s, String[] words) { List res = new ArrayList<>(); if (s == null || s.length() == 0 || words == null || words.length == 0) return res; int w = words[0].length(); int k = words.length; int totalLen = w * k; int n = s.length(); // 1. 统计目标单词 Map need = new HashMap<>(); for (String word : words) { need.put(word, need.getOrDefault(word, 0) + 1); } // 2. 核心:外层按偏移量分组 (0 到 w-1) for (int start = 0; start < w; start++) { int left = start; int right = start; int count = 0; // 满足的单词种类数 Map window = new HashMap<>(); // 3. 窗口内每次移动 w 长度 while (right + w <= n) { // 右边进一个单词 String word = s.substring(right, right + w); right += w; if (need.containsKey(word)) { window.put(word, window.getOrDefault(word, 0) + 1); if (window.get(word).equals(need.get(word))) { count++; } } // 如果窗口长度超过总长度,左边出一个单词 while (right - left > totalLen) { String leftWord = s.substring(left, left + w); left += w; if (need.containsKey(leftWord)) { if (window.get(leftWord).equals(need.get(leftWord))) { count--; } window.put(leftWord, window.get(leftWord) - 1); } } // 4. 判断是否刚好凑齐 if (right - left == totalLen && count == need.size()) { res.add(left); } } } return res; } }