I did this problem again today and tried a more efficient way. The runtime is reduced more than 10 times (32ms now). The idea is also using two unordered map to count the number of different words. But the loop now is different.
I use the start variable to loop just for the length of one word. And from this start, I check the whole string after to see if it contains a concatenation. The second loop is like a moving window.
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
if(s.empty()||words.empty())
return res;
int slen=s.length();
int wordLen=words[0].length();
int wordNum=words.size();
for(int i=0;i<wordNum;i++)
dict[words[i]]++;//initialize the dictionary for words
for(int start=0;start<wordLen;start++)
{
int i=start,j=start;
int count=0;
while(i<=slen-wordLen*wordNum&&j<=slen-wordLen)
{
auto it=dict.find(s.substr(j,wordLen));
if(it==dict.end())//this word is not in the dict, clear everything
{
count=0;
curr_table.clear();
i=j+wordLen;
}
else
{
curr_table[it->first]++;
count++;
while(curr_table[it->first]>it->second)
{
string temp=s.substr(i,wordLen);
curr_table[temp]--;
count--;
i+=wordLen;
}
if(count==wordNum)
res.push_back(i);
}
j+=wordLen;
}
curr_table.clear();
}
return res;
}
private:
unordered_map<string,int> dict,curr_table;
};