题目中没有说明,其实words中的单词都是等长的。
使用两个hashmap。对words
中的每个word
,用第一个map1
储存单词出现次数,key为单词,value为出现次数;
对于string s
,首先将其划分为words
总长度的子串,然后对于这每一个子串,用第二个map2
统计其中所有单词出现的次数,如果次数大于map1
中的次数(对于map1
中不存在的单词,map1[tempword]<map2[tempword]
始终为真),则说明一定不匹配。
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if (s.empty())
return vector<int>();
vector<int> res;
int wordSumLen = words.size() * words[0].length();
int singleLen = words[0].length();
//统计words中每个word出现的个数
map<string, int> map1;
for (auto word : words)
{
if (map1.count(word) == 0)
{
map1.insert(pair<string, int>(word, 1));
}
else
map1[word]++;
}
//wether the length of s is bigger than words
if(s.length()< wordSumLen)
return vector<int>();
for (int i = 0; i <= (s.length() - wordSumLen); i++)
{
string subS;
subS = s.substr(i, wordSumLen);
map<string, int> map2;
bool isMatch=1;
for (int j = 0; j < wordSumLen; j = j + singleLen)
{
string tempword;
tempword = subS.substr(j, singleLen);
//add to hashtable
if (map2.count(tempword) == 0)
{
map2.insert(pair<string, int>(tempword, 1));
}
else
map2[tempword]++;
if (map1[tempword] < map2[tempword])
{
isMatch = 0;
break;
}
}
if (isMatch)
res.push_back(i);
}
return res;
}
};