2 sliding window method


  • 3

    Array version:

        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.length() == 0) return 0;
            int left = 0, right = 0;
            int len = 0;
            int[] letter = new int[512];
            while (right < s.length()) {
                char c = s.charAt(right);
                if (letter[c] == 0) {
                    letter[c]++;
                    if (right - left + 1 > len) len = right - left + 1;
                    right++;
                } else {
                    letter[s.charAt(left)]--;
                    left++;
                }
            }
            return len;
        }
    

    HashSet version:

        public int lengthOfLongestSubstring(String s) {
            int left = 0, right = 0;
            int len = 0;
            Set<Character> set = new HashSet<>();
            while (right < s.length()) {
                if (!set.contains(s.charAt(right))) {
                    set.add(s.charAt(right++));
                    len = Math.max(len, set.size());
                } else {
                    set.remove(s.charAt(left++));
                }
            }
            return len;
        }
    

Log in to reply
 

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