-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxSubstringWithoutRepetitions.java
More file actions
71 lines (67 loc) · 2.37 KB
/
MaxSubstringWithoutRepetitions.java
File metadata and controls
71 lines (67 loc) · 2.37 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
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.HashMap;
import java.util.HashSet;
public class MaxSubstringWithoutRepetitions {
public static String find(String s){
if(s.equals("")) return "";
if(s == null) return null;
int max = 0;
int begin = 0;
HashSet<Character> found = new HashSet<Character>();
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length; i++){
//Impossible to find a bigger substring
if(chars.length - i < max) break;
found.clear();
found.add(chars[i]);
for(int j = i+1; j <= chars.length; j++){
if(j == chars.length){
int currentRange = j-i;
if(currentRange > max){
max = currentRange;
begin = i;
}
}
else if(found.contains(chars[j])){
int currentRange = j-i;
if(currentRange > max){
max = currentRange;
begin = i;
}
break;
}
else{
found.add(chars[j]);
}
}
}
if(max == 1) return chars[begin] + "";
return s.substring(begin, begin + max);
}
public static String find2(String s){
if(s.equals("")) return "";
if(s == null) return null;
HashMap<Character, Integer> found = new HashMap<Character,Integer>();
char[] chars = s.toCharArray();
int[] maxSoFar = new int[chars.length];
maxSoFar[0] = 1;
found.put(chars[0],0);
for(int i = 1; i < chars.length; i++){
if(found.containsKey(chars[i])){
maxSoFar[i] = Math.min(i - found.get(chars[i]), maxSoFar[i-1] + 1);
}
else{
maxSoFar[i] = maxSoFar[i-1] + 1;
}
found.put(chars[i],i);
}
int maxIndex = maxIndex(maxSoFar);
return s.substring(maxIndex - maxSoFar[maxIndex] + 1, maxIndex+1);
}
public static int maxIndex(int[] arr){
int max = 0;
for(int x : arr) max = x > max? x : max;
for(int i = 0; i < arr.length; i++)
if(arr[i] == max) return i;
return -1;
}
}