Easy Java O(n) using HashMaps


  • 1
    public int lengthOfLongestSubstring(String s) {
            HashMap<Character, Integer> used = new HashMap<Character,Integer>();
            int start = 0;
            int end = 0;
            int maxLength = 0;
            while(end<s.length()){
                char c = s.charAt(end);
                int indx = used.getOrDefault(c,-1);
                if(indx>=start){
                    start=indx+1;
                }
                used.put(c,end);
                maxLength = Math.max(maxLength,end-start+1);
                end++;
            }
            return maxLength;
        }
    

Log in to reply
 

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