Leetcode题解-30. 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 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).
题意
给一个字符串String和一组字符串string_list,string_list中的所有字符串长度一致。在String中寻找所有子串s,要求s是string_list中所有字符串的组合(不要求按照string_list中字符串存放的顺序),返回满足要求的子串第一个字符在String中的位置的集合。
思路
用两个map来解决,第一个map存放string_lsit中的字符串和对应的数量,第二个map存放子串中找到的string_list和对应的数量。对原字符串String从头开始遍历,以string_list的字符串的长度为步长,检查步长范围内的子串是否在string_list中且第二个map存放该子串的数量是否不大于第一个map存放该子串的数量,如果是则下一个步长,如果否则进入String的下一个字符。
代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
map<string, int> words_map;
int l = s.size(), num = words.size(), len = words[0].size();
for(int i = 0; i < num; i++){
words_map[words[i]]++;
}
for(int i = 0; i < l - num*len + 1; i++){
map<string, int> finded;
int j = 0;
for( ; j < num; j++){
string cur = s.substr(i + j*len, len);
if(words_map.find(cur) != words_map.end()){
finded[cur]++;
if(finded[cur] > words_map[cur]) break;
}
else break;
}
if(j == num)
res.push_back(i);
}
return res;
}
};