30. Substring with Concatenation of All Words
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> indices;
if (s.size() == 0 or words.size() == 0) return indices;
unordered_map<string, int> counts;
for (string word : words)
counts[word]++;
int n = s.size(), num = words.size(), len = words[0].length();
for (int i = 0; i <= n - num * len; i++) {
unordered_map<string, int> seen;
int j = 0;
for (; j < num; j++) {
string word = s.substr(i + j * len, len);
if (counts.find(word) != counts.end()) {
seen[word]++;
if (seen[word] > counts[word]) // overuse
break;
}
else break; // did not find
}
if (j == num) indices.push_back(i);
}
return indices;
}
};Last updated
Was this helpful?