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;
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。