判断给定的字符串是否存在一些子串由给定的words列表构成。
sol:
由于words里的每个单词的长度是一样的,举个例子吧
s长度为18 ,words每个单词长度为3
那么我们按照单词的长度来枚举
0, 3, 6, 9, 12, 15
1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
也就是说把源字符串按照words的单词长度切分后,再用滑动窗口的办法来做。
贴个别人的代码:
public class Solution {
/*
A time & space O(n) solution
Run a moving window for wordLen times.
Each time we keep a window of size windowLen (= wordLen * numWord), each step length is wordLen.
So each scan takes O(sLen / wordLen), totally takes O(sLen / wordLen * wordLen) = O(sLen) time.
One trick here is use count to record the number of exceeded occurrences of word in current window
*/
public static List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if(words == null || words.length == 0 || s.length() == 0) return res;
int wordLen = words[0].length();
int numWord = words.length;
int windowLen = wordLen * numWord;
int sLen = s.length();
HashMap<String, Integer> map = new HashMap<>();
for(String word : words) map.put(word, map.getOrDefault(word, 0) + 1);
for(int i = 0; i < wordLen; i++) { // Run wordLen scans
HashMap<String, Integer> curMap = new HashMap<>();
for(int j = i, count = 0, start = i; j + wordLen <= sLen; j += wordLen) { // Move window in step of wordLen
// count: number of exceeded occurences in current window
// start: start index of current window of size windowLen
if(start + windowLen > sLen) break;
String word = s.substring(j, j + wordLen);
if(!map.containsKey(word)) {
curMap.clear();
count = 0;
start = j + wordLen;
}
else {
if(j == start + windowLen) { // Remove previous word of current window
String preWord = s.substring(start, start + wordLen);
start += wordLen;
int val = curMap.get(preWord);
if(val == 1) curMap.remove(preWord);
else curMap.put(preWord, val - 1);
if(val - 1 >= map.get(preWord)) count--; // Reduce count of exceeded word
}
// Add new word
curMap.put(word, curMap.getOrDefault(word, 0) + 1);
if(curMap.get(word) > map.get(word)) count++; // More than expected, increase count
// Check if current window valid
if(count == 0 && start + windowLen == j + wordLen) {
res.add(start);
}
}
}
}
return res;
}
}
其他大佬的解法: