|
5 | 5 |
|
6 | 6 | /**
|
7 | 7 | * 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. |
22 | 19 | */
|
23 | 20 | 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; |
47 | 48 | }
|
48 |
| - maxLength = Math.max(maxLength, hi - lo); |
49 |
| - } |
50 |
| - return maxLength; |
51 | 49 | }
|
52 |
| - } |
53 | 50 | }
|
0 commit comments