30. Substring with Concatenation of All Words找子串
#难度:Difficulty: Hard
#题目:
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"]
(order does not matter).
You should return the indices: [0,9]
.
#题解:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> result;
int word_length=words[0].size();
//1
int words_length=words.size();
//2
int s_len=s.length();
//3
if(!s_len || words.empty()){
return vector<int>();
}
map<string,int> all_words;
//4
map<string,int> cur_word;
//5
for(auto &i : words){
//6
++all_words[i];
}
for(int i=0;i<=(s_len - word_length*words_length);i++){
//7
cur_word.clear();
int j=0;
for(j=0;j<words_length;j++){
//8
string tmp=s.substr(i+j*word_length,word_length);
//9
if(all_words.find(tmp)==all_words.end()){
//10
break;
}
++cur_word[tmp];
//11
if(cur_word[tmp]>all_words[tmp]){
//12
break;
}
}
if(j==words_length){
//13
result.push_back(i);
}
}
return result;
}
};
|
#题解注释:(懒得逐个上传图片了 - -)
#附注
基于范围的for循环
在C++03中,要遍历一个list中的元素需要很多代码.其它语言实现支持"糖块句法",允许程序通过一个简单的"foreach"语句自动遍历list中的元素.其中之一就是Java语言, 它从5.0开始支持增强的for循环.
C++11增加了一个类似的特性, for语句可以简单地遍历列表中的元素.
int my_array[5] = {1, 2, 3, 4, 5}; // double the value of each element in my_array:for (int &x : my_array) { x *= 2; }
这种形式的for语句叫作"基于范围的for语句",它会遍历列表中的每一个元素.可以用在C风格数组,初始化列表和那些带有能返回迭代器的begin()和end()函数的类型上.所有提供了begin/end的标准容器都可以使用基于范围的for语句.