实现代码:
import java.util.*;
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
if (s == null || s.isEmpty() || words == null || words.length == 0) {
return result;
}
int wordLength = words[0].length();
int substringLength = wordLength * words.length;
if (s.length() < substringLength) {
return result;
}
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
for (int i = 0; i <= s.length() - substringLength; i++) {
Map<String, Integer> currentCount = new HashMap<>();
int j = 0;
for (; j < words.length; j++) {
String word = s.substring(i + j * wordLength, i + (j + 1) * wordLength);
if (!wordCount.containsKey(word)) {
break;
}
currentCount.put(word, currentCount.getOrDefault(word, 0) + 1);
if (currentCount.get(word) > wordCount.get(word)) {
break;
}
}
if (j == words.length) {
result.add(i);
}
}
return result;
}
}