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).
给定一个字符串S和一个词典L, 从S中找出所有的子串的初始位置,这些子串有L中的所有单词组成,L中的每个单词只使用一次,子串中不包含词典以外的其他单词。注意:词典中所有单词的长度都一样
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> result;
int slen=S.length(); //字符串长度
int lsize=L.size(); //词典中的单词数
if(lsize==0)return result; //词典为空
int wordLen=L[0].length();
int window=lsize*wordLen;
if(slen<window)return result; //滑动窗口比S长
//初始化辅助map
map<string, int> dict;
for(int i=0; i<lsize; i++) dict[L[i]]+=1;
//搜索
for(int i=0; i<=slen-window; i++){
map<string, int> tempdict; //辅助当前窗口的map
int wordStart=i;
for(; wordStart<i+window; wordStart+=wordLen){
string word=S.substr(wordStart, wordLen);
if(dict[word]==0)break; //如果当前单词没有在字典中出现过,直接break
else if(dict[word]==tempdict[word])break; //如果当前单词已经出现过字典中指定的次数,说明当前单词是多出来的,直接break
else tempdict[word]+=1; //累计单词出现的次数
}
if(wordStart==i+window)result.push_back(i);
}
return result;
}
};LeetCode: Substring with Concatenation of All Words [029],布布扣,bubuko.com
LeetCode: Substring with Concatenation of All Words [029]
原文:http://blog.csdn.net/harryhuang1990/article/details/26070065