Substring with Concatenation of All Words
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.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
解题思路
使用一个 Hash Table 存放 words 中的单词(记为 wordMap),其中 key 为单词, value 为单词出现的次数。
枚举符合条件的子串可能的起始位置
i
。首先获得以
代码如下:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int wordNum = words.size();
int wordLen = words[0].size();
unordered_map<string, int> wordMap;
for (int i = 0; i< wordNum; ++i) {
wordMap[words[i]]++;
}
vector<int> result;
int end = s.size() - wordNum * wordLen;
for (int i = 0; i <= end; ++i) {
int j;
unordered_map<string, int> curMap;
for (j = 0; j < wordNum; ++j) {
string word = s.substr(i+j*wordLen, wordLen);
if (wordMap.find(word) == wordMap.end()) break;
curMap[word]++;
if (curMap[word] > wordMap[word]) break;
}
if (j == wordNum) {
result.push_back(i);
}
}
return result;
}
};