-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
More file actions
56 lines (41 loc) · 1.34 KB
/
LongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
56 lines (41 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package leetcode.solution.SlideWindow;
import java.util.HashMap;
import java.util.Map;
/**
* 3. Longest Substring Without Repeating Characters
*/
public class LongestSubstringWithoutRepeatingCharacters {
public static void main(String[] args) {
String s = "abcabcbb";
LongestSubstringWithoutRepeatingCharacters f = new LongestSubstringWithoutRepeatingCharacters();
int ans = f.lengthOfLongestSubstring(s);
System.out.println(ans);
//3
}
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
Map<Character, Integer> map = new HashMap<>();
int right = 0;
int left = 0;
while (right < s.length()) {
char toAdd = s.charAt(right);
right++;
int currentCount = map.getOrDefault(toAdd, 0);
currentCount++;
map.put(toAdd, currentCount);
while (currentCount > 1) {
char toRemove = s.charAt(left);
left++;
int existCount = map.get(toRemove);
map.put(toRemove, existCount - 1);
if (toRemove == toAdd) {
currentCount--;
}
}
if (right - left > maxLength) {
maxLength = right - left;
}
}
return maxLength;
}
}