1.4
This commit is contained in:
1 parent
c5025637ee
commit
ac5b43af95
4 files changed
+128
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package com.hong.www;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
class A30_2 {
|
||||
public List<Integer> findSubstring(String s, String[] words) {
|
||||
List<Integer> 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<String, Integer> 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<String, Integer> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user