You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S:
L:
S:
"barfoothefoobarman"
L:
["foo", "bar"]
You should return the indices:
(order does not matter).
---------------------------- thinking ---------------------------------------------[0,9]
.(order does not matter).
https://oj.leetcode.com/discuss/20151/an-o-n-solution-with-detailed-explanation
---------------------------- codes -------------------------------------------------
In this codes, be very careful about the updating of count!!! Which causes a lot of bugs
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> result;
if (L.size() == 0 || S.size() < L.size() * L[0].size()) {
return result;
}
unordered_map<string, int> map;
//initialize map
for (int i = 0; i < L.size(); i++) {
if (map.find(L[i]) == map.end()) {
map[L[i]] = 1;
} else {
map[L[i]]++;
}
}
//out loop
for (int loop = 0; loop < L[0].size(); loop++) {
unordered_map<string, int> dict = map;
int count = 0;
int start = loop;
for (int j = loop; j < S.size(); j+=L[0].size()) {
if (map.find(S.substr(j, L[0].size())) == map.end()) {
//bug here
start = j + L[0].size();
dict = map;
count = 0;
} else {
dict[S.substr(j, L[0].size())]--;
count++;
// bug here -> different from min sub win problem
if (dict[S.substr(j, L[0].size())] < 0) {
while (dict[S.substr(j,L[0].size())] < 0) {
dict[S.substr(start,L[0].size())]++;
// bug here -> different from min sub win problem
count--;
start += L[0].size();
}
}
if (count == L.size()) {
result.push_back(start);
dict[S.substr(start, L[0].size())]++;
start += L[0].size();
//bug here e.g. "abababab", ["a", "b", "a"]
count--;
}
}
}
}
return result;
}
};
No comments:
Post a Comment