Sharing my O(n) java Solution in 10 lines


  • 5
    V
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        if (s == null || s.length() == 0) return 0;
        if (s.length() == 1) return 1;
        int rightPointer = 0, leftPointer = rightPointer - 1, answer = 0;
        while (rightPointer != s.length()) {
            Integer previousOccurrence = map.put(s.charAt(rightPointer), rightPointer);
            if (previousOccurrence != null) {
                leftPointer = Math.max(leftPointer, previousOccurrence);
            }
            answer = Math.max(answer, rightPointer - leftPointer);
            rightPointer++;
        }
        return answer;
    }

Log in to reply
 

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