forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_159.java
71 lines (68 loc) · 2.23 KB
/
_159.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
65
66
67
68
69
70
71
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
public class _159 {
public static class Solution1 {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.length() < 1) {
return 0;
}
Map<Character, Integer> index = new HashMap<>();
int lo = 0;
int hi = 0;
int maxLength = 0;
while (hi < s.length()) {
if (index.size() <= 2) {
char c = s.charAt(hi);
index.put(c, hi);
hi++;
}
if (index.size() > 2) {
int leftMost = s.length();
for (int i : index.values()) {
leftMost = Math.min(leftMost, i);
}
char c = s.charAt(leftMost);
index.remove(c);
lo = leftMost + 1;
}
maxLength = Math.max(maxLength, hi - lo);
}
return maxLength;
}
}
public static class Solution2 {
/**
* My completely original solution, classic sliding window problem:
* use two pointers, one keeps moving towards the right to expand;
* the other moves only when we are no longer meeting the requirement, i.e. shrinks.
*/
public int lengthOfLongestSubstringTwoDistinct(String s) {
int distinct = 0;
int ans = 0;
int left = 0;
int right = 0;
int[] counts = new int[256];
while (right < s.length()) {
char c1 = s.charAt(right);
if (counts[c1] == 0) {
distinct++;
}
counts[c1]++;
right++;
if (distinct <= 2) {
ans = Math.max(ans, right - left);
}
while (distinct > 2) {
char c2 = s.charAt(left);
counts[c2]--;
if (counts[c2] == 0) {
distinct--;
}
left++;
}
}
return ans;
}
}
}