题目链接:leetcode 30
给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
例如,如果 words = [“ab”,“cd”,“ef”], 那么 “abcdef”, “abefcd”,“cdabef”, “cdefab”,“efabcd”, 和 “efcdab” 都是串联子串。 “acdbef” 不是串联子串,因为他不是任何 words 排列的连接。
返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。
1)示例 1:
输入:s = “barfoothefoobarman”, words = [“foo”,“bar”]
输出:[0,9]
解释:因为 words.length == 2 同时 words[i].length == 3,连接的子字符串的长度必须为 6。
子串 “barfoo” 开始位置是 0。它是 words 中以 [“bar”,“foo”] 顺序排列的连接。
子串 “foobar” 开始位置是 9。它是 words 中以 [“foo”,“bar”] 顺序排列的连接。
输出顺序无关紧要。返回 [9,0] 也是可以的。
2)示例 2:
输入:s = “wordgoodgoodgoodbestword”, words = [“word”,“good”,“best”,“word”]
输出:[]
解释:因为 words.length == 4 并且 words[i].length == 4,所以串联子串的长度必须为 16。
s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接。
所以我们返回一个空数组。
3)示例 3:
输入:s = “barfoofoobarthefoobarman”, words = [“bar”,“foo”,“the”]
输出:[6,9,12]
解释:因为 words.length == 3 并且 words[i].length == 3,所以串联子串的长度必须为 9。
子串 “foobarthe” 开始位置是 6。它是 words 中以 [“foo”,“bar”,“the”] 顺序排列的连接。
子串 “barthefoo” 开始位置是 9。它是 words 中以 [“bar”,“the”,“foo”] 顺序排列的连接。
子串 “thefoobar” 开始位置是 12。它是 words 中以 [“the”,“foo”,“bar”] 顺序排列的连接。
首先我们可以明确,假设某个串联子串在s的开始位置为pos,那么有如下结论
1)这个串联子串的长度为words[0].size()*words.size()
2)以words[0].size()对这个子串进行划分,每个单词应该存在于words中,且在words中出现的次数和在子串中出现的次数保持一致
为了确定每个划分的单词是否和words中的单词匹配,我们预先处理,确定对于0<=i
class Solution {
public:
int get_id(string s,vector<string>& words,int st,int num){
if(st<0) return -1;
string s_test=s.substr(st,num);
for(int i=0;i<words.size();i++)
if(s_test==words[i]) return i;return -1;
}
map<int,int> map2;
map<string,int> map3;
vector<string> words;
void get_map2(string s, vector<string>& words){
for(int i=0;i<s.size();i++)
map2[i]=-1;
for(int i=0;i+words[0].size()-1<s.size();i++)
for(int j=0;j<words.size();j++){
string s1=s.substr(i,words[0].size());
if(s1==words[j]) map2[i]=j;
}
}
void get_map3(string s, vector<string>& words2){
sort(words2.begin(),words2.end());
for(int i=0;i<words2.size();i++)
map3[words2[i]]=0;
for(int i=0;i<words2.size();i++){
map3[words2[i]]++;
if(i==0){
words.push_back(words2[i]);
continue;
}
if(words2[i]!=words2[i-1])
words.push_back(words2[i]);
}
}
vector<int> findSubstring(string s, vector<string>& words2) {
int words_length=words2[0].size();
int sum_length=words2.size()*words2[0].size();
get_map3(s,words2);
get_map2(s,words);
vector<int> ans;
for(int i=0;i<words_length;i++){
map<int,int> map1;
for(int j=-1;j<words.size();j++)
map1[j]=0;
for(int j=i;j+sum_length-1<s.size();j+=words_length)
{
bool flag=true;
int st1=j-words_length;
int st2=j+sum_length-words_length;
if(j==i){
for(int k=j;k<=st2;k+=words_length)
map1[map2[k]]++;
}
else{
map1[map2[st2]]++;map1[map2[st1]]--;
}
for(int k=0;k<words.size();k++)
if(map1[k]!=map3[words[k]]) {flag=false;}
if(flag==true) ans.push_back(j);
}
}
return ans;
}
};