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: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
Code:
<span style="font-size:14px;">class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
const int lengthS = S.size(), lengthL = L.size();
const int lengthWord = L[0].size();
vector<int> results;
unordered_map<string, int> hashTableL;
unordered_map<string, int> hashTableS;
for (int i = 0; i < lengthL; ++i)
hashTableL[L[i]]++;
bool succeed;
for (int i = 0; i <= lengthS-lengthL*lengthWord; ++i) {
hashTableS.clear();
succeed = true;
for (int j = 0; j < lengthL; ++j) {
string str = S.substr(i+j*lengthWord, lengthWord);
if (hashTableL.find(str) == hashTableL.end()) {
succeed = false;
break;
} else if (++hashTableS[str] > hashTableL[str]) {
succeed = false;
break;
}
}
if (succeed) results.push_back(i);
}
return results;
}
};</span>