October 19, 2019

3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Sliding Window. Time = O(n), space = O(n)

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        Set<Character> set = new HashSet<>();
        int l = 0;
        int r = 0;
        int max = 0;
        while (r < s.length()) {
            if (!set.contains(s.charAt(r))) {
                set.add(s.charAt(r));
                r++;
                max = Math.max(max, r - l);
            } else {
                set.remove(s.charAt(l));
                l++;
            }
        }
        return max;
    }
}
comments powered by Disqus