题目:串联所有单词的子串
给定一个字符串 s 和一个字符串数组 words 。 words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
- 例如,如果
words = ["ab","cd","ef"], 那么"abcdef","abefcd","cdabef","cdefab","efabcd", 和"efcdab"都是串联子串。"acdbef"不是串联子串,因为他不是任何words排列的连接。
返回所有串联字串在 s 中的开始索引。你可以以 任意顺序 返回答案。
示例 1:
输入: s = "barfoothefoobarman", words = ["foo","bar"]
输出: [0,9]
解释: 因为 words.length == 2 同时 words[i].length == 3,连接的子字符串的长度必须为 6。
子串 "barfoo" 开始位置是 0。它是 words 中以 ["bar","foo"] 顺序排列的连接。
子串 "foobar" 开始位置是 9。它是 words 中以 ["foo","bar"] 顺序排列的连接。
输出顺序无关紧要。返回 [9,0] 也是可以的。
示例 2:
输入: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
输出: []
解释: 因为 words.length == 4 并且 words[i].length == 4,所以串联子串的长度必须为 16。
s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接。
所以我们返回一个空数组。
示例 3:
输入: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
输出: [6,9,12]
解释: 因为 words.length == 3 并且 words[i].length == 3,所以串联子串的长度必须为 9。
子串 "foobarthe" 开始位置是 6。它是 words 中以 ["foo","bar","the"] 顺序排列的连接。
子串 "barthefoo" 开始位置是 9。它是 words 中以 ["bar","the","foo"] 顺序排列的连接。
子串 "thefoobar" 开始位置是 12。它是 words 中以 ["the","foo","bar"] 顺序排列的连接。
提示:
1 <= words.length <= 50001 <= words[i].length <= 30words[i]和s由小写英文字母组成
解题思路
采用两个map来存储目标单词组和遍历单词组(key = word, value = wordCount);结果中要求记录所有符合子串的左下标,显然窗口左边界不能大于s.length() - wordCount * step
- 滑动窗口长度为step;
- 窗口左边界还是每次右移left++;
- 判断每个窗口对应的word是否是目标word;并设计有效word计数器num < wordCount遍历。若最后num == wordCount,则完全符合;
- tempMap的每次修改后都判断指定word的value是否不大于wordMap中对应的value。若tempMap.get(word) > wordMap.get(word),退出循环,此时num < wordCount;出现不符合单词时,直接退出循环,此时只会num < wordCount和num == wordCount;
- 此解法避免了遍历比较两个map。
代码实现
public List < Integer > findSubstring(String s, String[] words) {
List < Integer > ans = new ArrayList < Integer > ();
if (null == words || words.length == 0) {
return ans;
}
// 用HashMap存放单词,value为其出现的次数(重复单词)
Map < String, Integer > wordMap = new HashMap < String, Integer > ();
for (String word: words) {
if (wordMap.containsKey(word)) {
wordMap.put(word, wordMap.get(word) + 1);
} else {
wordMap.put(word, 1);
}
}
int step = words[0].length();
int wordCount = words.length;
for (int left = 0; left <= s.length() - wordCount * step; left++) {
Map < String, Integer > tempMap = new HashMap < String, Integer > ();
// 记录出现优先单词的数量
int num = 0;
while (num < wordCount) {
String word = s.substring(left + num * step, left + (num + 1) * step);
if (wordMap.containsKey(word)) {
int value = tempMap.getOrDefault(word, 0);
tempMap.put(word, value + 1);
if (tempMap.get(word) > wordMap.get(word)) {
break;
}
} else {
break;
}
num++;
}
// 有效单词数量和目标数组单词数量一致,则表示完全相同
if (num == wordCount) {
ans.add(left);
}
}
return ans;
}
运行结果
复杂度分析
- 空间复杂度:O(1)
- 时间复杂度:O(n)
在掘金(JUEJIN) 一起分享知识, Keep Learning!