题目:
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
思路:
用哈希表存储L中的单词以及出现的次数,然后在S中取一个窗口,窗口大小为L[0].size() * L.size() ,窗口中的字符串每次取L[0].size() 长度的子串在哈希表中查找。如果窗口中的子串都能在哈希表中找到,则说明找到符合条件的,记录下来。
代码:
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L)
{
vector<int> result;
if(L.empty())
return result;
map<string , int> words;//哈希表,存储L中对应单词出现的次数
int wordLen = L[0].size();
int wordNum = L.size();
int len = wordLen * wordNum;
if(S.size() < len)
return result;
for(int i = 0 ; i < L.size() ; i++)
words[L[i]]++;
for(int i = 0 ; i <= S.size() - len ; i++)
{
map<string , int> curWords;//存储已经查找到的单词以及出现的次数,主要用于判断是否找到重复的单词
int j = i;
for( ; j < i+len ; j += wordLen)
{
string tmp = S.substr(j,wordLen);
if(words.find(tmp) == words.end()) //在words中没有发现,则直接中断当前循环
break;
curWords[tmp]++;//否则,在curWords中次数+1
if(curWords[tmp] > words[tmp])
break;
}
if(j == i+len)
result.push_back(i);
}
return result;
}
};