-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30. Substring with Concatenation of All Words.cpp
48 lines (48 loc) · 1.54 KB
/
30. Substring with Concatenation of All Words.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
// 267 ms
vector<int> findSubstring(string s, vector<string>& words) {
int wn = words.size();
int wl = words[0].size();
int sublen = wn*wl;
int n = s.size();
vector<int> indexes;
if(n<sublen)
return indexes;
vector<int> wstart(n,-1);
unordered_map<string, int> count;
for(int i=0;i<wn;++i) {
string& w = words[i];
count[w]++;
if(count[w]==1) { // finding str first time, search in s
std::string::size_type k=s.find(w);
while(k != std::string::npos){
wstart[k] = i;
k=s.find(w,k+1);
}
}
}
// start location
for (int i = 0; i < n - sublen + 1; i++) {
unordered_map<string, int> seen;
int j = 0;
int pos = i;
for (; j < wn; j++) {
if(wstart[pos] == -1)
break;
string& ss = words[wstart[pos]];
seen[ss]++;
if(seen[ss]> count[ss])
break;
pos +=wl;
}
if (j == wn) indexes.push_back(i);
}
return indexes;
}
};