Problem Statement:

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

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

Example 2:

Input: s = “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1.

Example 3:

Input: s = “dvdf” Output: 3 Explanation: The answer is “vdf”, with the length of 3. Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.

Solution:

1. HashMap Version
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0;
        int end = 0;
        int maxLength = 0;
        HashMap<Character, Integer> positionMap = new HashMap<>();
 
        while (end < s.length()) {
            Character ch = s.charAt(end);
			
			/*The use of `Math.max(start, positionMap.get(ch) + 1)` is crucial to 
			ensure the `start` pointer only moves forward and never backwards.*/
            if (positionMap.containsKey(ch)) {
                start = Math.max(start, positionMap.get(ch) + 1);
            }
 
            positionMap.put(ch, end);
            maxLength = Math.max(maxLength, end - start + 1);
            end++;
        }
        return maxLength;
    }
}
2. Set Version
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        Set<Character> window = new HashSet<>();
        
        int left = 0;
        int right = 0;
        while(right < s.length()) {
            char currentChar = s.charAt(right);
            
            // Contract the window until the duplicate is removed
            while (window.contains(currentChar)) {
                window.remove(s.charAt(left));
                left++;
            }
            
            // Add the current character to the window
            window.add(currentChar);
            
            // Update the maximum length of the substring
            maxLen = Math.max(maxLen, right - left + 1);
			right++;
        }
        
        return maxLen;
    }
}