Longest Substring Without Repeating Characters
Problem
Read one word. Print the length of the longest substring (continuous part) that has no repeated character.
Constraints
- 1 <= length <= 10^5, ASCII, no spaces
Examples
Input
abcabcbb
Output
3
Solutions
A window grows to the right. When the new character is already inside the window, the left side jumps past the old copy. Each character is visited once.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : Length of the longest unique window.
* Approach: Sliding window.
* Time : O(n)
* Space : O(k)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(String s) {
// Step 1: lastSeen remembers the last index of every character. -1 means: not seen yet.
int[] lastSeen = new int[256];
java.util.Arrays.fill(lastSeen, -1);
// Step 2: The window is s[left..right]. It never has a repeated character.
int left = 0;
int best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// Step 3: If c is already inside the window, move left behind its last position.
if (lastSeen[c] >= left) {
left = lastSeen[c] + 1;
}
// Step 4: Save the position of c and update the best length.
lastSeen[c] = right;
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Where must left move when a repeat is found?