![[leetcode]30. Substring with Concatenation of All Words由所有单词连成的子串 [leetcode]30. Substring with Concatenation of All Words由所有单词连成的子串](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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) in s that is a concatenation of each word in words exactly 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 = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []
题意:
给定一个无重复单词的字典D,和一个长字符串S。找出S中的子串,该子串恰好是D中所有单词连接而成。
code
/*
Time: O(n * m ). outter for loop to scan n items, inner for loop to scan m substrings
Space: O(m)
*/
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
// corner case
if (words.length == 0 || s.length() == 0) return result; int wordLength = words[0].length();
int catLength = wordLength * words.length; // 求Concatenation长度。 因为题干说words中每个单词长度一致。
// corner case
if (s.length() < catLength) return result; Map<String, Integer> map = new HashMap<>();
for (String word : words)
map.put(word, map.getOrDefault(word, 0) + 1); // words中有单词可能出现多次 // 终结到s.length() - catLength因为最后一部分catLength长度的串可能是一个valid Concatenation解
for (int i = 0; i <= s.length() - catLength; ++i) {
// deep copy
Map<String, Integer> checkingMap = new HashMap<>(map); for (int j = i; j < i + catLength; j = j + wordLength) {
final String key = s.substring(j, j + wordLength);
final int freq = checkingMap.getOrDefault(key, -1); if (freq == -1 || freq == 0) break; checkingMap.put(key, freq - 1);
if (freq - 1 == 0) checkingMap.remove(key);
} if (checkingMap.size() == 0) result.add(i);
}
return result;
}
}