8000 refactor 159 · eutopian/Leetcode@2a49859 · GitHub
[go: up one dir, main page]

Skip to content 8000

Commit 2a49859

Browse files
refactor 159
1 parent 90b503d commit 2a49859

File tree

1 file changed

+39
-28
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+39
-28
lines changed
Lines changed: 39 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,53 @@
11
package com.fishercoder.solutions;
22

33
import java.util.HashMap;
4+
import java.util.Map;
45

56
/**
6-
* Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
7+
* 159. Longest Substring with At Most Two Distinct Characters
78
8-
For example, Given s = “eceba”,
9+
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
910
10-
T is "ece" which its length is 3.
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.
1122
*/
1223
public class _159 {
13-
24+
public static class Solution1 {
1425
public int lengthOfLongestSubstringTwoDistinct(String s) {
15-
if (s.length() < 1) {
16-
return 0;
26+
if (s.length() < 1) {
27+
return 0;
28+
}
29+
Map<Character, Integer> index = new HashMap<>();
30+
int lo = 0;
31+
10000 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++;
1738
}
18-
HashMap<Character, Integer> index = new HashMap<Character, Integer>();
19-
int lo = 0;
20-
int hi = 0;
21-
int maxLength = 0;
22-
while (hi < s.length()) {
23-
if (index.size() <= 2) {
24-
char c = s.charAt(hi);
25-
index.put(c, hi);
26-
hi++;
27-
}
28-
if (index.size() > 2) {
29-
int leftMost = s.length();
30-
for (int i : index.values()) {
31-
leftMost = Math.min(leftMost, i);
32-
}
33-
char c = s.charAt(leftMost);
34-
index.remove(c);
35-
lo = leftMost + 1;
36-
}
37-
maxLength = Math.max(maxLength, hi - lo);
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;
3847
}
39-
return maxLength;
48+
maxLength = Math.max(maxLength, hi - lo);
49+
}
50+
return maxLength;
4051
}
41-
52+
}
4253
}

0 commit comments

Comments
 (0)
0