###### LeetCode 159. Longest Substring with At Most Two Distinct Characters(java)

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = “eceba”,

T is "ece" which its length is 3.
###### 用start2和start1来标志包括两个元素的头和只包括一个元素的头，然后iterate直到i,每次i位置都分情况讨论。
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.length() == 0) return 0;
int start2 = 0;
int start1 = 0;
int result = 1;

for (int i = 1; i < s.length(); i++) {
if ( s.charAt(i) != s.charAt(i-1)) {
if (start1 == 0 || s.charAt(i) != s.charAt(start1 - 1)) {
start2 = start1;
}
start1 = i;
}
result = Math.max(result, i - start2 + 1);
}
return result;
}
//follow up : exactly 2 distinct characters
//int start2;
//start2可能会不取值，当一直为一个值时。

#### Java学习指南系列（Java快速入门）

2017年08月09日 15:30

#### leetcode 159: Longest Substring with At Most Two Distinct Characters

2015-01-28 04:05:56

#### [LeetCode] Longest Substring with At Most Two Distinct Characters及扩展

2015-01-06 04:24:08

#### LeetCode 340. Longest Substring with At Most K Distinct Characters（最长字串）

2016-04-30 09:10:31

#### [leetcode] 340. Longest Substring with At Most K Distinct Characters 解题报告

2016-04-03 12:28:01

#### Longest Substring with At Most K Distinct Characters

2016-03-29 21:16:24

#### [leetcode] 159. Longest Substring with At Most Two Distinct Characters 解题报告

2016-03-18 13:38:51

#### leetcode:3. Longest Substring Without Repeating Characters (java)

2016-06-20 20:36:28

#### LeetCode(3) Longest Substring Without Repeating Characters

2013-11-23 04:25:39

#### [LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C++/Java/Python)

2015-02-27 12:55:12

## 不良信息举报

LeetCode 159. Longest Substring with At Most Two Distinct Characters(java)