3. Longest Substring Without Repeating Characters

time: O(n)

space: O(n)

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // ecounter same, for loop i, j index = map.get(same) + 1
        if (s == null || s.length() == 0) return 0;
        
        int res = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0, j = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            res = Math.max(res, i - j + 1);
        }
        return res;
        
    }
}

Last updated