-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuniqueSubarrayString.java
57 lines (53 loc) · 1.67 KB
/
uniqueSubarrayString.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
// Given a String, find the longest substring with unique characters.
// For example: "whatwhywhere" --> "atwhy"
// time - O(n)
// space - O(2) ~ O(1)
import java.util.HashMap;
public class uniqueSubarrayString {
public static int[] findUnique(String str){
if(str.isEmpty()){
return null;
}
if(str.length() == 1){
int ans[] = new int[2];
ans[0] = 0;
ans[1] = 0;
return ans;
}
int start = 0;
int end = 0;
int maxLength = Integer.MIN_VALUE;
int[] ans = new int[2];
HashMap<Character, Integer> map = new HashMap<>();
map.put(str.charAt(0), 0);
while(end < str.length() - 1){
end++;
if(map.containsKey(str.charAt(end)) && map.get(str.charAt(end)) >= start){
start = map.get(str.charAt(end)) + 1;
}
map.put(str.charAt(end), end);
if(end - start + 1 > maxLength){
maxLength = end - start + 1;
ans[0] = start;
ans[1] = end;
}
}
return ans;
}
public static void main(String[] args) {
String inputString = "whatwhywhere";
int[] resultArray = findUnique(inputString);
if(resultArray == null){
System.out.print("Empty input array");
}
else{
for(int i = 0 ; i < resultArray.length ; i++){
if(resultArray[i] == -1){
System.out.print("Subarray not available");
break;
}
System.out.print(resultArray[i] + " ");
}
}
}
}