-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestSubstringWithoutDuplication.java
54 lines (52 loc) · 1.52 KB
/
LongestSubstringWithoutDuplication.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
import java.util.*;
// Solution 1
class Program {
// O(n) time | O(min(m,n)) space - where n is the length of the string and m is the size of the charset
public static String longestSubstringWithoutDuplication(String str) {
// Write your code here
if (str.length() == 0) {
return "";
}
int[] longestRange = {0, 1};
Map<Character, Integer> dict = new HashMap<>();
int l = 0;
for (int r = 0; r < str.length(); r++) {
char ch = str.charAt(r);
dict.put(ch, dict.getOrDefault(ch, 0) + 1);
while (dict.getOrDefault(ch, 0) > 1) {
dict.put(str.charAt(l), dict.get(str.charAt(l)) - 1);
l++;
}
if (r + 1 - l > longestRange[1] - longestRange[0]) {
longestRange[0] = l;
longestRange[1] = r + 1;
}
}
return str.substring(longestRange[0], longestRange[1]);
}
}
// Solution 2
class Program {
// O(n) time | O(min(m, n)) space - where n is the length of the string and m is the size of the charset
public static String longestSubstringWithoutDuplication(String str) {
// Write your code here
if (str.length() == 0) {
return "";
}
int[] longestRange = {0, 1};
Map<Character, Integer> lastSeen = new HashMap<>();
int l = 0;
for (int r = 0; r < str.length(); r++) {
char ch = str.charAt(r);
if (lastSeen.containsKey(ch)) {
l = Math.max(l, lastSeen.get(ch) + 1);
}
if (r + 1 - l > longestRange[1] - longestRange[0]) {
longestRange[0] = l;
longestRange[1] = r + 1;
}
lastSeen.put(ch, r);
}
return str.substring(longestRange[0], longestRange[1]);
}
}