LeetCode刷题_c++版-3无重复字符的最长子串

知识点

双指针维护窗口
hash_map

代码

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]]="<
            //每向后一个,最长长度加1
            maxLength++;
            //如果最后字符无重复,将hash表中该字符的映射置为1
            if(char_map.find(s[end]) == char_map.end() || char_map[s[end]] == 0) {
                //cout<<" "<
                char_map[s[end]] = 1;
                
                
            }
            //如果有重复,将begin向后移动,直至无重复为止
            else if(char_map[s[end]] == 1){
                //cout<<" "<
                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;

    }
};

结果

LeetCode刷题_c++版-3无重复字符的最长子串_第1张图片

你可能感兴趣的:(Leetcode,刷题,c++,leetcode,算法,开发语言,数据结构)