โ† Back to Index

๐Ÿ”‘ Longest Substring Without Repeating Characters โ€“ Java Cheat Sheet (One Page)

๐Ÿ“Œ What Is It?

The problem involves finding the length of the longest substring in a string `s` that contains no repeating characters.

๐Ÿงฑ Pattern Template

public int lengthOfLongestSubstring(String s) {
        Map lastSeen = new HashMap<>();
        int maxLen = 0;
        int left = 0;

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);

            if (lastSeen.containsKey(c) && lastSeen.get(c) >= left) {
                left = lastSeen.get(c) + 1; // jump left forward
            }

            lastSeen.put(c, right);
            maxLen = Math.max(maxLen, right - left + 1);
        }

        return maxLen;
}

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Longest Substring Without Repeating Characters

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

๐Ÿ’ก Pro Tips