串联所有单词的字串

给定一个字符串 s 和一个字符串数组 words words 中所有字符串 长度相同

s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。

  • 例如,如果 words = ["ab","cd","ef"], 那么 "abcdef""abefcd""cdabef""cdefab""efabcd", 和 "efcdab" 都是串联子串。 "acdbef" 不是串联子串,因为他不是任何 words 排列的连接。

返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。

示例 1:

1
2
3
4
5
6
输入: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:

1
2
3
4
5
输入:s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
输出:[]
解释:因为 words.length == 4 并且 words[i].length == 4,所以串联子串的长度必须为 16。
s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接。
所以我们返回一个空数组。

示例 3:

1
2
3
4
5
6
输入: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 <= s.length <= 10^4
  • 1 <= words.length <= 5000
  • 1 <= words[i].length <= 30
  • words[i]s 由小写英文字母组成

  • 建立一个统计words里单词出现次数的哈希表。
  • 每次循环维护一个窗口,窗口的长度等于words的长度。每一次循环将窗口右移一格,直到窗口到达s右端点。
  • 建立哈希表统计窗口中单词出现次数,如果两个哈希表相等,把起始坐标加入答案数组中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res; //结果数组
int d=words[0].size(); // 单词长度
int m=words.size(); // 单词个数
int len=m*d; // 单词总长度
unordered_map<string,int> word;
for(auto i:words) word[i]++; //初始化word哈希表
for(int i=0;i+len<=s.size();i++){ // 遍历每一个窗口
unordered_map<string,int> window;
int j=i; //记录窗口起始坐标
while(j<i+len) { //遍历窗口
auto sub=s.substr(j,d);
window[sub]++;
j+=d;
}
if(window==word) res.push_back(i);
}
return res;
}
};

这个解法枚举了所有的固定大小的窗口,最坏可能性外层循环s.size()次,内层循环len次,所以时间复杂度是O(s.size()*m*d)。10的9次方级别的运算量,很容易超时。

时间复杂度主要来自于外层循环,仔细观察发现其实窗口只有d种情况,窗口的起点是[0,d-1]。其余所有窗口都是这d窗口平移nd得到的。那么外层循环次数就可以优化为d次。

在每一轮循环维护一个滑动窗口,记录左边界,右边界和窗口内单词数,维护一个哈希表window记录窗口内的单词出现次数。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
int m=words.size();
int d=words[0].size();
int len=m*d;
unordered_map<string,int> word;
for(auto i:words) word[i]++;
for(int i=0;i<d;i++){
unordered_map<string,int> window;
int left=i,right=i,count=0;
while(right+d<=s.size()){
auto t=s.substr(right,d);
right+=d;
if(word.find(t)!=word.end()){
window[t]++;
count++;
while(window[t]>word[t]){
auto leftword=s.substr(left,d);
window[leftword]--;
left+=d;
count--;
}
if(count==m) res.push_back(left);
}
else{
left=right;
window.clear();
count=0;
}
}
}
return res;
}
};

时间复杂度O(d)*O(s.size()/O(d))=O(s.size())