-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstringwithConcatenationofAllWords.cpp
More file actions
56 lines (51 loc) · 1.84 KB
/
substringwithConcatenationofAllWords.cpp
File metadata and controls
56 lines (51 loc) · 1.84 KB
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
49
50
51
52
53
54
55
56
// Source: https://leetcode.com/problems/substring-with-concatenation-of-all-words/
// Author: Miao Zhang
// Date: 2021-01-07
/************************************************************************
* sliding window
* words_dict == {word: cnt}
* left is from 0 to s.size - lenOfWord * numsOfWords + 1
* right is from left to lenOfWord * numsOfWords
* cur_dict collects the contents from left to right
************************************************************************/
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
if (words.size() <= 0) {
return res;
}
unordered_map<string, int> words_dict;
for (auto word: words) {
if (words_dict.find(word) != words_dict.end()) {
words_dict[word]++;
} else {
words_dict[word] += 1;
}
}
int n = s.size(), lenOfWord = words[0].size(), numsOfWords = words.size();
for (int left = 0; left < n - lenOfWord * numsOfWords + 1; left++) {
int right = 0;
unordered_map<string, int> cur_dict;
while (right < numsOfWords) {
string word = s.substr(left + lenOfWord * right, lenOfWord);
if (words_dict.find(word) == words_dict.end()) {
break;
}
if (cur_dict.find(word) != cur_dict.end()) {
cur_dict[word]++;
} else {
cur_dict[word] += 1;
}
if (cur_dict[word] > words_dict[word]) {
break;
}
right++;
}
if (right == numsOfWords) {
res.push_back(left);
}
}
return res;
}
};