beat 59% results. and easy to understand!


  • 0
    C
    public int lengthOfLongestSubstring(String s) {
     
        if(s.length() == 0) return 0;
        int per = 0;
        int maxLen = 0;
        int len = s.length();
        Set<Character> set = new HashSet<>();
    
        for(int i = 0; i < s.length();i++){
            if(set.contains(s.charAt(i))){
                char cur = s.charAt(i);
                while(s.charAt(per) != cur){
                    set.remove(s.charAt(per));
                    per++;
                }
                per++;
            }else{
                set.add(s.charAt(i));
            }
            
            maxLen = Math.max(maxLen, i-per+1);
           
        }
    
        return maxLen;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.