3. Longest Substring Without Repeating Characters !

Sliding Window; HashMap

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Sliding Window & HashMap
        int result = 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        
        // set i as the the left edge and j is the right edge (included);
        for (int i=0, j=0; j<s.length(); j++){
            if(map.containsKey(s.charAt(j))){
                // make sure i never moved backward;
                i = Math.max(i, map.get(s.charAt(j))+1);
            }
            // always calculate the result even if the current char is in the map,
            // as duplication might because of the char before i
            result = Math.max(result, j-i+1);
            map.put(s.charAt(j),j);
        }
        
        return result;
    }
}

Last updated