Java Solution | Used Set and Sliding Window


  • 0
    M
        public int lengthOfLongestSubstring(String s) {
            
            String longestUniqueSub = "";
            String sub = "";
            int len = longestUniqueSub.length();
            
            Set<Character> chars = new HashSet<Character>();
            
            char[] s_chars = s.toCharArray();
            
            int left = 0, right = 0;
            
            while (right < s_chars.length) {
                
                if (!chars.contains(s_chars[right])) {
                    sub = sub + s_chars[right];
                    chars.add(s_chars[right]);
                    
                    if (sub.length() > longestUniqueSub.length()) {
                        longestUniqueSub = sub;
                        len = longestUniqueSub.length();
                    }
                    
                } else {                
                   
                    // System.out.println(longestUniqueSub);
                    while (left < s_chars.length && s_chars[left] != s_chars[right]) {
                        chars.remove(s_chars[left]);
                        left++;                    
                    }
                    left++;
                    sub = s.substring(left, right) + s_chars[right];            
                }                
                right++;
            }
            
            return len;
        }
    

  • 0
    T

    @manav.bhanot.86 said in Java Solution | Used Set and Sliding Window:

    s_chars[left] != s_chars[right

    This one clear to me


Log in to reply
 

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