Post

[Java] Longest Substring Without Repeating Characters

Feel free to leave a comment or contact me if you spot any errors or have feedback. I’m always open to learning!

[Java] Longest Substring Without Repeating Characters

LeetCode Problem #3 🔗 LeetCode Link

  • Time Complexity: O(n), n: s.length()
  • Space Complexity: O(n), n: s.length()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int begin = 0;
        int end = 0;
        int maxLength = 0;

        Set<Character> letterSet = new HashSet<>();
        while (end < s.length()) {
            // if the letter is not in the hashset, then add it into hashset and move end pointer
            if (!letterSet.contains(s.charAt(end))) {
                letterSet.add(s.charAt(end));
                ++end;
                maxLength = Math.max(maxLength, end - begin); // update maxlength
            } else { // if the letter is in the hashset, then remove it and move begin pointer
                letterSet.remove(s.charAt(begin));
                ++begin;
            }
        }
        
        return maxLength;
    }
}
This post is licensed under CC BY 4.0 by the author.