You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.spa
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
code
You should return the indices: [0,9]
.
(order does not matter).blog
// class Solution { void helper(string s, int lenword, int totallen, unordered_map<string, int>& ht, unordered_map<string, int>& ht_bk, vector<int>& allsol){ for (int i = 0; i<= s.size() - totallen; i++){ int j; for (j = i; j <= i + totallen - lenword; j += lenword){ string tmp = s.substr(j, lenword); //if (ht.count(tmp) && ht[tmp] > 0 ){ if (ht[tmp] > 0 ){ ht[tmp]--; }else{ break; } } // !! to clear the ht ht = ht_bk; if (j == i + totallen){ allsol.push_back(i); } } return; } public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> allsol; int sol = 0; int start; if (words.empty() || s.empty()) return allsol; unordered_map<string, int> ht; unordered_map<string, int> ht_bk; int n = s.size(); int lenword = words[0].size(); int ntotalwords = words.size(); int totallen = ntotalwords * lenword; if (n < totallen) return allsol; for (int i = 0; i < words.size(); i++){ ht[words[i]]++; } ht_bk = ht; helper(s, lenword, totallen, ht, ht_bk,allsol); return allsol; } };