You are given a string,s, and a list of words,words, that are all of the same length. Find all starting indices of substring(s) insthat is a concatenation of each word inwordsexactly once and without any intervening characters.
Example 1:
Input:
s =
"barfoothefoobarman",
words =
["foo","bar"]
Output:
[0,9]
Explanation:
Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s =
"wordgoodstudentgoodword",
words =
["word","student"]
Output:
[]
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> ans = new ArrayList<>();
if (s == null || words == null || words.length == 0) return ans;
Map<String, Integer> hash = new HashMap<>();
for (String word : words){
hash.put(word, hash.getOrDefault(word, 0) + 1);
}
int len = words[0].length();
for (int i = 0; i <= s.length() - words.length * len; i++){
Map<String, Integer> copy = new HashMap<>(hash);
for (int j = 0; j < words.length; j++){
String temp = s.substring(i + j * len, i + j * len + len);
if (copy.containsKey(temp)){
int count = copy.get(temp);
if (count == 1){
copy.remove(temp);
}
else{
copy.put(temp, copy.get(temp) - 1);
}
}
else break;
}
if (copy.size() == 0) ans.add(i);
}
return ans;
}
}