Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

Leetcode link

``

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] map = new int[256]; //Map the character to the first occurence index
int max = 0;
int slow = 0;

Arrays.fill(map,-1);

for (int fast = 0; fast < s.length(); fast++){
char current = s.charAt(fast);

if (slow <= map[current]){
max = Math.max(max, fast - slow);
slow = map[current] + 1;
}

map[current] = fast;
}

max = Math.max(max, s.length() - slow);

return max;
}
}