LeetCode brush questions_c++ version-3 The longest substring without repeating characters

knowledge points

Double pointer maintenance window
hash_map

the code

class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        //双指针维护窗口
        int begin = 0;
        int end = 0;
        int result = 0;
        int maxLength = 0;
        map<char, int>char_map;
        //当end未到达最后时,持续循环
        while(end < s.length()){
    
    
            //cout<<"char_map[s[end]]="<<s[end];
            //每向后一个,最长长度加1
            maxLength++;
            //如果最后字符无重复,将hash表中该字符的映射置为1
            if(char_map.find(s[end]) == char_map.end() || char_map[s[end]] == 0) {
    
    
                //cout<<" "<<char_map[s[end]]<<"+1"<< endl;
                char_map[s[end]] = 1;
                
                
            }
            //如果有重复,将begin向后移动,直至无重复为止
            else if(char_map[s[end]] == 1){
    
    
                //cout<<" "<<char_map[s[end]]<<"-1"<<endl;
                while(char_map[s[end]] == 1){
    
    
                    char_map[s[begin]] --;
                    begin++;
                    maxLength--;
                }char_map[s[end]] ++;
            }
            //如果更新后的最长串大于历史最长串,则更新result
            if(maxLength > result) result = maxLength ;
            end++;
        }
        return result;

    }
};

result

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44343355/article/details/129135230