30. Substring with Concatenation of All Words
题目
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.
给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
Example
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.
Input:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
Output: []
解法
- 使用map存储words即数量
- 计算word的长度length
- 从s的位置0开始搜索,每次取出length的子串substring,若map里存在substring,且数量大于0,那么数量-1,并继续取出下一个length的子串循环操作;若不满足,则接着从s的下一个位置开始搜索
- 如果所有的word在一次搜索中全找到,在把开始搜索的位置插入结果
注意:
- 判断s长度为0和words为0的情况
- s的位置从0到 s.length-words.length*length, 后边的不用再搜索
- 每次从一个新的s位置开始搜索时,要new一个新的mapcopy,不能直接等于
代码
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if(s.length() == 0 || words.length == 0)
return res;
// 计算每个word长度
int length = words[0].length();
int end = s.length() - words.length * length + 1;
// 把words放入map并计数
Map<String, Integer> wordsMap = new HashMap<>();
for(int i = 0; i < words.length; i++) {
if(wordsMap.containsKey(words[i])) {
wordsMap.put(words[i], wordsMap.get(words[i])+1);
}
else {
wordsMap.put(words[i], 1);
}
}
for(int i = 0; i < end; i++) {
Map<String, Integer> copy = new HashMap<>(wordsMap);
int k = i;
int j = 0;
for(; j < words.length; j++) {
String word = s.substring(k, k+length);
if(copy.containsKey(word) && copy.get(word) > 0) { // 存在且数量大于0
k += length; // 下一个子串开始的位置
copy.put(word, copy.get(word)-1);
}
else // 不存在,跳出循环,继续s的下一个位置
break;
}
// 所有word均找到
if(j == words.length)
res.add(i);
}
return res;
}
执行用时 : 223 ms, 在Substring with Concatenation of All Words的Java提交中击败了50.96% 的用户
内存消耗 : 37.6 MB, 在Substring with Concatenation of All Words的Java提交中击败了46.90% 的用户