0.思路
一道本科期间就做过的滑动窗口,但是忘了。
最近哈希用的很爽,八股背的也很多,自然而然从【重复】这个关键字就想到了哈希去重。为了尽可能降低时间复杂度,最好是遍历一遍就结束。
【思路概要】:当目前遍历的字符已经在哈希表中出现过,那从哈希表中记录的出现位置往后,都是可以复用的,所以窗口头begin应该挪到重复的元素的后一个。窗口尾end同时负责遍历整个字符串。
可以用测试用例"abcabcbb"来理解【思路概要】。当end遍历到s[3]也就是第二个a时,这时候a已经作为key存在于hashmap中了,查出上一个a的下标序号为0,那么滑动窗口头begin就从s[0]开始,这也就达成了「复用」。同时需要更新一下hashmap中记录的位置。
有一个tricky的地方是,当提交之后出现了字符串 "abba",我写的打印输出的结果为:
Now len=1 Now (begin,end) is (0,0) update lend to1 Now len=1 Now (begin,end) is (0,1) update lend to2 Now len=2 Now (begin,end) is (2,2) update lend to2 Now len=2 Now (begin,end) is (1,3) update lend to3
可以看到,最后一次的begin竟然比倒数第二次begin来的小,这就很不合常理。原因是,当我因为碰到了b重复时,只对b进行了更新,而下次碰到a重复时,更新begin完全依赖于a上一次出现的位置,这就导致begin会回退。所以采用begin=max(begin,chSet.find(c)->second+1);确保整个流程不会倒行逆施。
1.代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size()<1) return 0;
// set去重 + 遍历
unordered_map<char,int> chSet;//key-char value-index
int begin=0,end=0;
int len=end-begin+1;
for(char c:s){
// 新的字符
// end++;
cout<<"Now len="<<len<<endl;
if(chSet.find(c)!=chSet.end()){
// 有重复 复用从重复位置开始下一个的一段
// 对于 abba的情况,如果直接用begin=chSet[c]+1,会导致begin回退,
// 但是end不会回退,所以要取max,保证begin只会增加不会减少
begin=max(begin,chSet.find(c)->second+1);
// begin=chSet.find(c)->second+1;
// 更新hash
chSet.erase(c);
chSet.insert({c,end});
cout<<"Now (begin,end) is ("<<begin<<","<<end<<")"<<endl;
len=max(len,end-begin+1);//在end发生变化前就更新len
cout<<"update lend to"<<len<<endl;
end++;
}
else{
//没重复 扩大 存如hash
chSet.insert({c,end});
cout<<"Now (begin,end) is ("<<begin<<","<<end<<")"<<endl;
len=max(len,end-begin+1);
cout<<"update lend to"<<len<<endl;
end++;
}
}
return len;
}
};
2.自言自语
最近的算法能力和动脑水平明显下降了,无语住了,这样下去不行不行。
四月,再努力一个月,这一定是个收获的月份。