Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e349be2

Browse files
refactor 159
1 parent ac7ad51 commit e349be2

File tree

1 file changed

+38
-41
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+38
-41
lines changed

src/main/java/com/fishercoder/solutions/_159.java

Lines changed: 38 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -5,49 +5,46 @@
55

66
/**
77
* 159. Longest Substring with At Most Two Distinct Characters
8-
9-
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
10-
11-
Example 1:
12-
13-
Input: "eceba"
14-
Output: 3
15-
Explanation: t is "ece" which its length is 3.
16-
17-
Example 2:
18-
19-
Input: "ccaabbb"
20-
Output: 5
21-
Explanation: t is "aabbb" which its length is 5.
8+
* Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
9+
*
10+
* Example 1:
11+
* Input: "eceba"
12+
* Output: 3
13+
* Explanation: t is "ece" which its length is 3.
14+
*
15+
* Example 2:
16+
* Input: "ccaabbb"
17+
* Output: 5
18+
* Explanation: t is "aabbb" which its length is 5.
2219
*/
2320
public class _159 {
24-
public static class Solution1 {
25-
public int lengthOfLongestSubstringTwoDistinct(String s) {
26-
if (s.length() < 1) {
27-
return 0;
28-
}
29-
Map<Character, Integer> index = new HashMap<>();
30-
int lo = 0;
31-
int hi = 0;
32-
int maxLength = 0;
33-
while (hi < s.length()) {
34-
if (index.size() <= 2) {
35-
char c = s.charAt(hi);
36-
index.put(c, hi);
37-
hi++;
38-
}
39-
if (index.size() > 2) {
40-
int leftMost = s.length();
41-
for (int i : index.values()) {
42-
leftMost = Math.min(leftMost, i);
43-
}
44-
char c = s.charAt(leftMost);
45-
index.remove(c);
46-
lo = leftMost + 1;
21+
public static class Solution1 {
22+
public int lengthOfLongestSubstringTwoDistinct(String s) {
23+
if (s.length() < 1) {
24+
return 0;
25+
}
26+
Map<Character, Integer> index = new HashMap<>();
27+
int lo = 0;
28+
int hi = 0;
29+
int maxLength = 0;
30+
while (hi < s.length()) {
31+
if (index.size() <= 2) {
32+
char c = s.charAt(hi);
33+
index.put(c, hi);
34+
hi++;
35+
}
36+
if (index.size() > 2) {
37+
int leftMost = s.length();
38+
for (int i : index.values()) {
39+
leftMost = Math.min(leftMost, i);
40+
}
41+
char c = s.charAt(leftMost);
42+
index.remove(c);
43+
lo = leftMost + 1;
44+
}
45+
maxLength = Math.max(maxLength, hi - lo);
46+
}
47+
return maxLength;
4748
}
48-
maxLength = Math.max(maxLength, hi - lo);
49-
}
50-
return maxLength;
5149
}
52-
}
5350
}

0 commit comments

Comments
 (0)