159. Longest Substring with At Most Two Distinct Characters

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.
p1, p2 表示某個char最後一次出現的地方.
longest substring可能只包含一種char, 或者兩種char.
1. 只包含一種Char, 強制保持p1 == p2
2. 出現兩種char, 保證p1 <= p2, 爲了計算方便
3. 出現第三種char的時候,i - (p1+1) + 1 = i- p1 直接計算出當前substring長度。同時保證p1<=p2.
public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if(s == null || s.length() == 0) return 0;
        int p1 = 0, p2 = 0, len = 1, max = 1;
        char[] arr = s.toCharArray();
        for(int i = 1; i < arr.length; i++){
            // third char appear
            if(p1 != p2 && arr[i] != arr[p1] && arr[i] != arr[p2]){
                if(len > max) max = len;
                len = i - p1;
                p1 = p2;
                p2 = i;
            } else {
                // same char as p1 and p2
                if(arr[i] == arr[p1]){
                    p1 = p1 == p2 ? i : p2;
                }
                len++;
                p2 = i;
            }
        }
        if(len > max) max = len;
        return max;
    }
}
相關文章
相關標籤/搜索