-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestSubstring.java
64 lines (51 loc) · 1.42 KB
/
LongestSubstring.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.leetcode.algorithms.medium.string;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class LongestSubstring {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
// Print result
System.out.println(lengthOfLongestSubstring(input));
scanner.close();
}
static int lengthOfLongestSubstring(String s) {
if (s.length() <= 1) {
return s.length();
} else {
// Count substring without repeating characters and store as 'list'
Map<Character, Integer> map = new HashMap<Character, Integer>();
List<Integer> list = new ArrayList<Integer>();
Integer count = 0;
// i = start index of substring
for (int i = 0; i < s.length(); i++) {
String substr = s.substring(i, s.length());
char[] chars = substr.toCharArray();
for (int j = 0; j < chars.length; j++) {
if (map.containsKey(chars[j])) {
// update list
list.add(count);
// reset map and count
map.clear();
count = 0;
break;
} else {
map.put(chars[j], 1);
++count;
}
}
}
if (count > 0) {
list.add(count);
}
// Sort 'list' to get longest substring without repeating characters
Collections.sort(list);
return list.get(list.size() - 1);
}
}
}