-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode03.java
More file actions
78 lines (67 loc) · 1.8 KB
/
Copy pathleetcode03.java
File metadata and controls
78 lines (67 loc) · 1.8 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
72
73
74
75
76
77
78
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
String prevMax = "";
for (int i = 0; i < s.length(); i++) {
int index = prevMax.indexOf(s.charAt(i));
if (-1 == index) {
prevMax += s.charAt(i);
} else {
prevMax = prevMax.substring(index + 1, prevMax.length()) + s.charAt(i);
}
max = max > prevMax.length() ? max : prevMax.length();
}
return max;
}
/**
* via set remove to check whether to get the top element. this can rewrite with
* map
*
* Set only one special element.
*/
public int lengthOfLongestSubstring2(String s) {
int i = 0, j = 0, ans = 0;
Set<Character> set = new HashSet<Character>();
while (i < s.length() && j < s.length()) {
if (!set.contains(s.charAt(j))) {
ans = Math.max(ans, j - i + 1);
set.add(s.charAt(j++));
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
/**
* Use map to store the first i position.
*
* 1. store each element into map with its position;
* 2. check whether map has
* this element, if not, store it; otherwise, reset i position to map value + 1;
*/
public int lengthOfLongestSubstring3(String s) {
int i = 0, j = 0, ans = 0;
int n = s.length();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (j = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
public int lengthOfLongestSubstring4(String s) {
int n = s.length(), ans = 0;
int[] index = new int[128];
// current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
i = Math.max(index[s.charAt(j)], i);
ans = Math.max(ans, j - i + 1);
index[s.charAt(j)] = j + 1;
}
return ans;
}
}