题意
在串s中找一个连续的子串,要求words数组中的单词每个都要出现一次(重复的单词要多次出现),返回子串的起始下标
题解
用map保存单词及其出现的次数,然后枚举s的各个起始下标,找words中的各个单词。(如何找到单词且其剩余数目大于0,则继续查找下一个单词)
代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int slen = s.length();
int sublen = words[0].length();
int size = words.size();
map<string, int> word_count;
for(int i = 0; i < size; i++)
{
if(!word_count.count(words[i]))
word_count[words[i]] = 1;
else
word_count[words[i]]++;
}
vector<int> result;
for (int i = 0; i < slen; i++)
{
int count = 0;
int j = i;
map<string,int> temp(word_count);
if(j > slen - size * sublen)
break;
while (j <= slen - sublen)
{
string substr = s.substr(j, sublen);
if (temp.count(substr) && temp[substr] > 0) // if count>0
{
temp[substr]--;
j += sublen;
count ++;
}
else
break;
}
if (count == size)
result.push_back(i);
}
return result;
}
};