Skip to content

Commit 38486fe

Browse files
committed
Add 'Substring with Concatenation of All Words' solution.
1 parent 0ee9369 commit 38486fe

2 files changed

+79
-3
lines changed

Longest_Substring_Without_Repeating_Characters.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ class Solution {
1616
for (int i=0; i<256; i++)
1717
isAppeared[i] = false;
1818

19-
// To maintain a sliding window, in where each characters at most appears
20-
// once.
19+
// To maintain a sliding window, in where each characters at most appears
20+
// once.
2121
int l = 0, r = 0, result = 0;
2222
while (r < s.length()) {
2323
while (isAppeared[s[r]]) {
@@ -31,4 +31,4 @@ class Solution {
3131
}
3232
return result;
3333
}
34-
};
34+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
Substring with Concatenation of All Words
3+
You are given a string, S, and a list of words, L, that are all of the same
4+
length. Find all starting indices of substring(s) in S that is a
5+
concatenation of each word in L exactly once and without any intervening
6+
characters.
7+
8+
For example, given:
9+
S: "barfoothefoobarman"
10+
L: ["foo", "bar"]
11+
12+
You should return the indices: [0,9].
13+
(order does not matter).
14+
*/
15+
16+
class Solution {
17+
public:
18+
// Increase reference
19+
int increase(unordered_map<string, int> &hash, string key) {
20+
if (hash.find(key) == hash.end()) {
21+
hash.insert(pair<string, int>(key, 1));
22+
} else {
23+
hash[key] = hash[key] + 1;
24+
}
25+
return hash[key];
26+
}
27+
28+
// Decrease reference
29+
int decrease(unordered_map<string, int> &hash, string key) {
30+
if (hash.find(key) == hash.end())
31+
return -1;
32+
if (hash[key] == 1) {
33+
hash.erase(key);
34+
return 0;
35+
}
36+
hash[key] = hash[key] - 1;
37+
return hash[key];
38+
}
39+
40+
vector<int> findSubstring(string S, vector<string> &L) {
41+
vector<int> result;
42+
unordered_map<string, int> toFind, found;
43+
int n = L.size(), m = L[0].length();
44+
45+
for (int i=0; i<n; i++)
46+
increase(toFind, L[i]);
47+
48+
for (int delta=0; delta<m; delta++) {
49+
if (delta + n * m > S.length()) break;
50+
found.clear();
51+
int l = delta, r = delta;
52+
while (r < S.length()) {
53+
string s = S.substr(r, m);
54+
r += m;
55+
56+
if (toFind.find(s) == toFind.end()) {
57+
found.clear();
58+
l = r;
59+
continue;
60+
}
61+
62+
increase(found, s);
63+
while (found[s] > toFind[s]) {
64+
string tmp = S.substr(l, m);
65+
decrease(found, tmp);
66+
l += m;
67+
}
68+
69+
if (r - l == n * m)
70+
result.push_back(l);
71+
}
72+
}
73+
74+
return result;
75+
}
76+
};

0 commit comments

Comments
 (0)