输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
/*
* @lc app=leetcode.cn id=3 lang=cpp
*
* [3] 无重复字符的最长子串
*/
// @lc code=start
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//ans means max length of s
int ans=0;
//hash table provides checking mechanism
unordered_map<char,int> need;
//two pointers,right means to search,if moving is not to add repeat,continue to move
//left means to shrink, proving decent window from left to right
int left=0,right=0;
int sz=s.size();
//end condition
while(right<sz){
char c=s[right];
++right;
++need[c];
//repre repeat chars in hash
//judges the repeat.-----need[c]>1
while(need[c]>1){
//fix it,from left to right
char d=s[left];
left++;
//when left moves,hash table need delete d until d equals to c
--need[d];
}
//calc current length
ans=max(ans,right-left);
}
//when iteration finish, return answer
return ans;
}
};
算法:为了找到字符串s的最长子串(连续的子序列),意味着从头到尾的遍历需要记录不重复的最长长度,双指针形成一个滑动窗口,当不重复时右指针滑动去探测更大的长度,重复时左指针为了消除这种重复,遍历到没有重复字符时的位置。(OS:因为你不能改变位置。)
哈希表在滑动窗口的过程中很重要,它保证滑动窗口的机制。什么时候可以继续加,什么时候需要缩小,什么时候可以退出,是滑动窗口算法的重要工具。
滑动窗口用同向双指针和哈希实现,左指针永远不会超过右指针,两个while语句搞定通用的滑动窗口。