Java O(n) Solution


  • 0
    R
       public int lengthOfLongestSubstring(String s) {
            if (s.length() == 0)
                return 0;
            HashMap<Character , Integer> hm = new HashMap<>();
            int j = 0;
            int [] max = new int [2];
            max[0] = 0;
            max[1] = 0;
    
            for (int i=0; i<s.length(); i++){
                if (!hm.containsKey(s.charAt(i))){
                    hm.put(s.charAt(i) , i);
    
                    if ((max[1]-max[0]) < (i-j)){
                        max[0] = j;
                        max[1] = i;
                    }
                }
                else {
                    if (j < hm.get(s.charAt(i))+1)
                    j = hm.get(s.charAt(i))+1;
                    if ((max[1]-max[0]) < (Math.abs(i-j))){
                        max[0] = j;
                        max[1] = i;
                    }
                    hm.put(s.charAt(i) , i);
                }
            }
            return s.substring(max[0] , max[1]+1).length();
            
        }
    

Log in to reply
 

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