The longest substring of leetcode without repeated characters-sliding window solution

Given a string, please find out the length of the longest substring that does not contain repeated characters.

Example 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3

Example 2:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

Code:

class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        int fre[256] = {
    
    0};
        int l = 0, r = -1;
        int res = 0;
        while(l < s.size()){
    
    
            if(r+1 < s.size() && fre[s[r+1]] == 0){
    
    
                fre[s[++r]] ++;
            }else{
    
    
                fre[s[l]] --;
                l++;
            }
            res = max(res, r-l+1);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/UCB001/article/details/106827533