Leetcode 3. Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
s
?
We’ll use the Sliding Window technique combined with a HashMap to efficiently track the characters and their most recent positions. Here’s the plan:
int
variable maxLength
for the result.int
variable start
to track the starting index of the current window.HashMap<Character, Integer>
to store the most recent position of each character.HashMap
.HashMap
and its position is within the current window (start
to the current index), update start
to be one more than this position to ensure no duplicates.HashMap
with the current position of the character.maxLength
if this window is larger.import java.util.HashMap;
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int maxLength = 0;
int start = 0;
HashMap<Character, Integer> charIndexMap = new HashMap<>();
for (int end = 0; end < s.length(); end++) {
char currentChar = s.charAt(end);
// If character is in the map and its index is within the current window
if (charIndexMap.containsKey(currentChar) && charIndexMap.get(currentChar) >= start) {
start = charIndexMap.get(currentChar) + 1;
}
charIndexMap.put(currentChar, end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.lengthOfLongestSubstring("abcabcbb")); // Output: 3
System.out.println(sol.lengthOfLongestSubstring("bbbbb")); // Output: 1
System.out.println(sol.lengthOfLongestSubstring("pwwkew")); // Output: 3
System.out.println(sol.lengthOfLongestSubstring("")); // Output: 0
System.out.println(sol.lengthOfLongestSubstring("abcdefg")); // Output: 7
}
}
The time complexity of this solution is O(n), where n
is the length of the string:
HashMap
operations (get and put) both run in constant time, O(1).for
loop iterates through the string once, making the overall complexity linear.This approach efficiently finds the length of the longest substring without repeating characters by maintaining a sliding window over the string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?