-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestUniqueSubstring.java
More file actions
59 lines (46 loc) · 1.32 KB
/
LongestUniqueSubstring.java
File metadata and controls
59 lines (46 loc) · 1.32 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
57
58
59
/****
*
* Length of the longest substring
*
* Given a string S, find the length of the longest substring without repeating characters.
*
* Input:
* S = "abdefgabef"
*
* Output:
* 6
*
* Explanation:
* Longest substring are
* "abdefg" , "bdefga" and "defgab".
*
*/
import java.util.HashMap;
import java.util.Map;
public class LongestUniqueSubstring {
public static void main(String[] arge) {
LongestUniqueSubstring longestUniqueSubstring = new LongestUniqueSubstring();
System.out.println(longestUniqueSubstring.longestUniqueSubsttr("aaaaaaaaaa"));
}
int longestUniqueSubsttr(String input) {
Map<Character, Integer> map = new HashMap<>();
int maxLength = 0;
int currentLength = 0;
for (int i = 0; i < input.length(); ) {
char ch = input.charAt(i);
Integer index = map.get(ch);
if (index == null) {
map.put(ch, i);
currentLength++;
i++;
} else {
if (currentLength > maxLength) {
maxLength = currentLength;
}
currentLength = 0;
i = index + 1;
}
}
return Math.max(maxLength, currentLength);
}
}