Skip to content

Commit 34945da

Browse files
committed
3
1 parent 6a85900 commit 34945da

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
class Solution {
2+
public:
3+
// 1612ms
4+
vector<int> findSubstring(string S, vector<string> &L) {
5+
// Start typing your C/C++ solution below
6+
// DO NOT write int main() function
7+
8+
int M = L.size();
9+
int N = L[0].size();
10+
11+
vector<int> indices;
12+
if (S.size() < M * N) return indices;
13+
14+
map<string, int> words_dict;
15+
for (int i = 0; i < M; i++)
16+
words_dict[L[i]] += 1;
17+
18+
for (int i = 0; i <= S.size() - M*N; i++) {
19+
map<string, int> has_found;
20+
bool flag = true;
21+
for (int j = 0; j < M; j++) {
22+
string sub_string = S.substr(i + j * N, N);
23+
if (words_dict.find(sub_string) == words_dict.end()) {
24+
flag = false; break;
25+
}
26+
has_found[sub_string] += 1;
27+
if (has_found[sub_string] > words_dict[sub_string]) {
28+
flag = false; break;
29+
}
30+
}
31+
if (flag) indices.push_back(i);
32+
}
33+
return indices;
34+
}
35+
};
36+
37+
//
38+
// Solution2 : 1356ms
39+
//
40+
class Solution {
41+
public:
42+
vector<int> findSubstring(string S, vector<string> &L) {
43+
// Start typing your C/C++ solution below
44+
// DO NOT write int main() function
45+
46+
int M = L.size();
47+
int N = L[0].size();
48+
49+
vector<int> indices;
50+
if (S.size() < M * N) return indices;
51+
52+
map<string, int> words_dict;
53+
for (int i = 0; i < M; i++)
54+
words_dict[L[i]] += 1;
55+
56+
for (int i = 0; i < N; i++) {
57+
vector<string> substrings;
58+
for (int j = i; j + N <= S.size(); j += N)
59+
substrings.push_back(S.substr(j, N));
60+
for (int j = 0; j + M <= substrings.size(); j++) {
61+
map<string, int> has_found;
62+
bool flag = true;
63+
for (int k = 0; k < M; k++) {
64+
if (words_dict.find(substrings[j+k]) == words_dict.end()) {
65+
flag = false; break;
66+
}
67+
has_found[substrings[j+k]] += 1;
68+
if (has_found[substrings[j+k]] > words_dict[substrings[j+k]]) {
69+
flag = false; break;
70+
}
71+
}
72+
if (flag) indices.push_back(i + j * N);
73+
}
74+
}
75+
return indices;
76+
}
77+
};

0 commit comments

Comments
 (0)