3. Longest Substring Without Repeating Characters
Intitution
Complexity
Space Complexity
Time Complexity
Code
public int lengthOfLongestSubstring(String input) {
// Array to keep track of seen characters in the current window
boolean[] isCharSeen = new boolean[256];
int maxSubstringLength = 0;
// Sliding window boundaries
for (int windowStart = 0, windowEnd = 0; windowEnd < input.length(); ++windowEnd) {
// If character at windowEnd has already been seen, shrink the window from the start
while (isCharSeen[input.charAt(windowEnd) - '\0'] && windowStart < windowEnd) {
isCharSeen[input.charAt(windowStart++) - '\0'] = false;
}
// Update the maximum length if this window is longer
maxSubstringLength = Math.max(windowEnd - windowStart + 1, maxSubstringLength);
// Mark the current character as seen
isCharSeen[input.charAt(windowEnd) - '\0'] = true;
}
return maxSubstringLength;
}
Last updated