串联所有单词的字串题解
有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出:[0,9]
题解:
暴力就不考虑了,我第一种方法是,破产版的滑动窗口,每次滑动一个字符,用两个map<string,int>一个dict存words,一个tmp存当前滑动窗的单词。然后确定tmp的单词对应匹配数是否在dict可以找到,挨个由于words的单词长度都一样,我想直接每次跳length_words进行匹配,显然会丢结果。而且效果真的丢人。提交里空间和时间都是倒数5%。嘿嘿,把我都气笑了。
看了前面的代码,顿悟,滑动窗口的正确姿势。
滑动每次肯定是要按leng_word来滑动的,同时采用leng_word次外部循环确保不漏情况。为什么是leng_word次呢?既然是找子串,而且子串长度必然是leng_word的倍数,则外部循环只需按照leng_word的余数作为起始即可。
前者和后者时间复杂度分析分别是O(N2),O(mn)m=leng_word,后者避免了很多不必要的计算。
贴代码:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int>res;
unsigned int length=words.size();
if(s.empty()||words.empty())return res;
unsigned int ea_leng=words[0].size();
if(!ea_leng)return res;
unsigned int wins=ea_leng*length;
unordered_map<string,int> dict;
for (auto &a:words)++dict[a];
if (s.size()<wins)
return res;
unsigned int s_leng=s.size();
//滑动窗口思想
unsigned int st,ed;
st=0;ed=0;
for(int i=0;i<ea_leng;i++)
{
unordered_map<string,int> temp;
st=i;
ed=st;
while(ed+ea_leng<=s_leng)
{
string bs=s.substr(ed,ea_leng);
ed+=ea_leng;
if(dict.find(bs)==dict.end())
{
st=ed;
temp.clear();
}
else
{
++temp[bs];
if(temp[bs]>dict[bs])
{
while(temp[bs]>dict[bs])
{
string buf=s.substr(st,ea_leng);
--temp[buf];
st+=ea_leng;
}
}
if(ed-st==wins)
res.push_back(st);
}
}
}
return res;
}
};
第一名是8ms,而且方法很独特,明天看看,再另外分析。