|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.HashMap;
|
| 4 | +import java.util.Map; |
4 | 5 |
|
5 | 6 | /**
|
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 |
7 | 8 |
|
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. |
9 | 10 |
|
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. |
11 | 22 | */
|
12 | 23 | public class _159 {
|
13 |
| - |
| 24 | + public static class Solution1 { |
14 | 25 | 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 | + 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++; |
17 | 38 | }
|
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; |
38 | 47 | }
|
39 |
| - return maxLength; |
| 48 | + maxLength = Math.max(maxLength, hi - lo); |
| 49 | + } |
| 50 | + return maxLength; |
40 | 51 | }
|
41 |
| - |
| 52 | + } |
42 | 53 | }
|
0 commit comments