Jack Li's Blog

0003.Longest Substring Without Repeating Character

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int i = 0;
        int ans = 0;
        Set<Character> existSet = new HashSet<>();

        for(int j = 0; j < n; j++) {
            Character c = s.charAt(j);
            
            while(existSet.contains(c)) {
                existSet.remove(s.charAt(i));
                i++;
            }
            
            existSet.add(c);
            ans = Math.max(ans, j - i + 1);
        }

        return ans;
    }
}