当前位置:网站首页>Leetcode-3: Longest substring without repeated characters

Leetcode-3: Longest substring without repeated characters

2022-07-05 06:09:00 Chrysanthemum headed bat

leetcode-3: Longest substring without repeating characters

subject

Topic linking
Given a string s , Please find out that there are no duplicate characters in it Longest substrings The length of .

Example 1:

 Input : s = "abcabcbb"
 Output : 3 
 explain :  Because the longest substring without repeating characters is  "abc", So its length is  3.

Example 2:

 Input : s = "bbbbb"
 Output : 1
 explain :  Because the longest substring without repeating characters is  "b", So its length is  1.

Example 3:

 Input : s = "pwwkew"
 Output : 3
 explain :  Because the longest substring without repeating characters is  "wke", So its length is  3.
      Please note that , Your answer must be   Substring   The length of ,"pwke"  Is a subsequence , Not substring .

Problem solving

Method 1 : Sliding window and hash collection

class Solution {
    
public:
    int lengthOfLongestSubstring(string s) {
    
        int res=INT_MIN;
        unordered_set<char> set;
        int left=0,right=0;
        while(right<s.size()){
    
            if(set.count(s[right])==0){
    
                set.insert(s[right]);
                right++;
            }
            else{
    
                set.erase(s[left]);
                left++;
            }
            res=max(res,right-left);
        }
        if(res==INT_MIN) return 0;
        else return res;
    }
};
原网站

版权声明
本文为[Chrysanthemum headed bat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050546085226.html