0
点赞
收藏
分享

微信扫一扫

Offer II 016. 不含重复字符的最长子字符串

左手梦圆 2022-03-11 阅读 38

题目描述

给定一个字符串 s ,请你找出其中不含有重复字符的 最长连续子字符串 的长度。

滑动窗口(滑,就嗯滑)利用hashmap来判断是否重复出现

代码

#include<hash_map>
using namespace __gnu_cxx;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        hash_map<char,int> hashmap;
        int max = 0;
        int count = 0;
        int left = 0, right = 0;
        for(int i=0;i<s.length();i++){
            if(hashmap.count(s[right]) == 0){
                 hashmap.insert(make_pair(s[right],0));
            }
        }
        while(right < s.length()){
            //cout<<left<<endl;
            if(hashmap[s[right]] == 0){
                //不存在
                hashmap[s[right]]++;
                count ++;
                if(count > max) max= count;
                right++;
            }
            else{
                hashmap[s[left]]--;
                left++;
                count--;
            }
        }
        return max;
    }
};
举报

相关推荐

0 条评论