-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathLongestNonRepetitiveSubstring.java
49 lines (43 loc) · 1.26 KB
/
LongestNonRepetitiveSubstring.java
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
package com.thealgorithms.strings;
import java.util.HashMap;
import java.util.Map;
final class LongestNonRepetitiveSubstring {
private LongestNonRepetitiveSubstring() {
}
public static int lengthOfLongestSubstring(String s) {
int max = 0;
int start = 0;
int i = 0;
Map<Character, Integer> map = new HashMap<>();
while (i < s.length()) {
char temp = s.charAt(i);
// adding key to map if not present
if (!map.containsKey(temp)) {
map.put(temp, 0);
} else if (s.charAt(start) == temp) {
start++;
} else if (s.charAt(i - 1) == temp) {
if (max < map.size()) {
max = map.size();
}
map = new HashMap<>();
start = i;
i--;
} else {
if (max < map.size()) {
max = map.size();
}
while (s.charAt(start) != temp) {
map.remove(s.charAt(start));
start++;
}
start++;
}
i++;
}
if (max < map.size()) {
max = map.size();
}
return max;
}
}