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).
Code:
<span style="font-size:14px;">class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
const int lengthS = S.size(), lengthL = L.size();
const int lengthWord = L[0].size();
vector<int> results;
unordered_map<string, int> hashTableL;
unordered_map<string, int> hashTableS;
for (int i = 0; i < lengthL; ++i)
hashTableL[L[i]]++;
bool succeed;
for (int i = 0; i <= lengthS-lengthL*lengthWord; ++i) {
hashTableS.clear();
succeed = true;
for (int j = 0; j < lengthL; ++j) {
string str = S.substr(i+j*lengthWord, lengthWord);
if (hashTableL.find(str) == hashTableL.end()) {
succeed = false;
break;
} else if (++hashTableS[str] > hashTableL[str]) {
succeed = false;
break;
}
}
if (succeed) results.push_back(i);
}
return results;
}
};</span>

本文介绍了一种高效的字符串匹配算法,该算法能在给定的字符串S中找到由单词列表L构成的所有子串的起始索引,其中L中的所有单词长度相同且每个单词恰好使用一次。

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



