25
04/2015
[LeetCode] Substring with Concatenation of All Words
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 wordsexactly 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).
解题思路:
1、最开始考虑用DFS的办法,将words组合成一个长串,然后用KMP查找,超时错误。到网上查找了相关的代码,大体就是滑动窗口的思想。讲解见http://bangbingsyb.blogspot.com/2014/11/leetcode-substring-with-concatenation.html。
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> allPos;
if(L.empty()) return allPos;
int totalWords = L.size();
int wordSize = L[0].size();
int totalLen = wordSize * totalWords;
if(S.size()<totalLen) return allPos;
unordered_map<string,int> wordCount;
for(int i=0; i<totalWords; i++)
wordCount[L[i]]++;
for(int i=0; i<=S.size()-totalLen; i++) {
if(checkSubstring(S, i, wordCount, wordSize, totalWords))
allPos.push_back(i);
}
return allPos;
}
bool checkSubstring(string S, int start, unordered_map<string,int> &wordCount, int wordSize, int totalWords) {
if(S.size()-start+1 < wordSize*totalWords) return false;
unordered_map<string,int> wordFound;
for(int i=0; i<totalWords; i++) {
string curWord = S.substr(start+i*wordSize,wordSize);
if(!wordCount.count(curWord)) return false;
wordFound[curWord]++;
if(wordFound[curWord]>wordCount[curWord]) return false;
}
return true;
}
};
0 条评论