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;
}
};
本文介绍了如何解决字符串中包含所有单词的子串问题,通过使用哈希表来优化匹配过程,确保每个单词恰好出现一次且不包含任何间隔字符。详细解释了解题思路并提供了代码实现。
753

被折叠的 条评论
为什么被折叠?



