[leetcode] 3. Longest Substring Without Repeating Characters 解题报告

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路:一道很经典的字符串处理的题目,借助一个hash数组,维护一个不包含重复字符串的窗口,使用左右指针left, right滑动窗口大小。左右指针的滑动规则如下:

1. 首先右指针right向右滑动,直到遇到一个和窗口中重复的字符。右指针在滑动过程中更新最大不重复子串的长度

2. 此时向右移动左指针,使得左指针移动到重复字符之后去,同时左指针向右移动的过程中更新hash表的字母计数。再重复1的操作直到遍历完字符,即可找到最大子串长度。

时间复杂度为O(n),空间复杂度为O(n)。

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() ==0) return 0;
        int left =0, Max =0;
        unordered_map<char, bool> hash;
        for(int i = 0; i< s.size(); i++)
        {
            while(hash.count(s[i])) hash.erase(s[left++]);
            hash[s[i]] = true;
            Max = max(Max, (int)hash.size());
        }
        return Max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值