您的位置:首页 > 其它

[LeetCode]Substring with Concatenation of All Words

2015-11-12 15:51 555 查看
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).

找到匹配words的子串,采用hash map的方法。

采用两个hash map对比可以确定是否是子串。

class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int wordlen = words[0].size();
int strlen = s.size();
vector<int> result;
map<string,int> temp;
map<string,int> Count;
if(strlen < wordlen*words.size())
return result;
for(int i=0;i<words.size();++i){
++temp[words[i]];
}

for(int i=0; i<=strlen-wordlen*words.size(); ++i){ //important bondary
Count.clear(); //count the word we found
int j=i;
for(; j<i+wordlen*words.size(); j=j+wordlen){
string se = s.substr(j,wordlen);
if(temp.count(se) != 0){
++Count[se];
if(Count[se]>temp[se])
break;
}
else break;
}

if(j>=i+wordlen*words.size()){
result.push_back(i);
}

}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: