Leetcode 3:无重复字符的最长子串

题目
输入: 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语句搞定通用的滑动窗口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值