Java 7 lines fast and simple solution with explanation


  • 1
    Y
    b := begin index inclusive
    e := end index exclusive
    map[c] := number of character c in s.substring(b, e)
    

    The algorithm works as follows:
    Whenever we want to append another char c to the substring, we need to remove chars from beginning of the substring until c is no longer in the substring.

        public int lengthOfLongestSubstring(String s) {
            int b = 0, e = 0, max = 0, map[] = new int[1<<7];
            while (e < s.length()) {
                while (map[s.charAt(e)] > 0) map[s.charAt(b++)]--;
                map[s.charAt(e++)]++;
                max = Math.max(max, e - b);
            }
            return max;
        }
    

Log in to reply
 

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