30 Substring with Concatenation of All Words
s: "barfoothefoobarman"
words: ["foo", "bar"]unordered_map<string, int> getWordFreq(const vector<string> &words) {
unordered_map<string, int> word_freq;
word_freq.reserve(words.size());
for (const string &s : words) {
if (word_freq.find(s) != word_freq.end())
word_freq[s]++;
else word_freq.insert({ s, 1 });
}
return word_freq;
}
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> substringSeq;
if (words.empty()) return substringSeq;
const size_t word_length = words.at(0).length();
unordered_map<string, int> word_freq = getWordFreq(words);
unordered_map<string, int> word_freq_cp = word_freq;
const int total_word_dist = words.size() * word_length;
const int end = s.length() - total_word_dist + 1;
for (int i = 0; i < end; i++) {
string cmplt_words = s.substr(i, total_word_dist);
for (int j = 0; j < total_word_dist; j += word_length) {
string cur_word = cmplt_words.substr(j, word_length);
if (word_freq_cp.find(cur_word) == word_freq_cp.end())
break;
else {
word_freq_cp[cur_word]--;
if (word_freq_cp[cur_word] == 0)
word_freq_cp.erase(cur_word);
}
}
if (word_freq_cp.empty())
substringSeq.push_back(i);
word_freq_cp = word_freq;
}
return substringSeq;
}Last updated