Skip to content

Latest commit

 

History

History
72 lines (58 loc) · 1.8 KB

3无重复字符的最长子串.md

File metadata and controls

72 lines (58 loc) · 1.8 KB

题目描述

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例1:

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

示例2:

输入:"bbbbb"
输出:1
解释:因为无重复字符的最长子串是 "b",所以其长度为 1。

示例3:

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


思路一(48.29%)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
       
        int len = s.length();
        
        if( len==0 ) return 0;
        if( len==1 ) return 1;
        
        set<char> ch;
        int maxLength = 0;
        int i = 0;
        ch.insert(s[0]);
        
        int j = 0;
        while(++j)
        {
            if( j>=len ) break;
            
            // found duplicate char
            if( ch.count(s[j]) ){
                //cout << "found duplicate : " << s[j] << endl;
                if( j-i > maxLength ) maxLength = j-i;
                
                for(;;){
                    if( s[i] == s[j] ){
                        
                        i++;
                        break;
                    }
                    else{
                        ch.erase(s[i]);
                        i++;
                    }
                }
            }
            else{
                ch.insert(s[j]);
            }    
                
        }
        
        
        if( j-i>maxLength ) return j-i;
        else return maxLength;
    }
};