Friday, November 27, 2015

[leetcode] Longest Substring with At Most Two Distinct Characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s == null || s.length() == 0) return 0;
        if (s.length() == 1) return 1;
        char c1 = s.charAt(0);
        char c2 = s.charAt(1);
        int i1 = 0;
        int i2 = 0;
        int length = 2;
        for (int i = 2; i < s.length(); i++){
            char current = s.charAt(i);
            if (current != c1 && current != c2){
                c1 = current;
                c2 = s.charAt(i-1);
                i1 = i;
                i2 = i-1;
                while (i2 >= 0&&s.charAt(i2) == c2){
                    i2--;
                }
                i2++;
            }
            length = Math.max(length, i-Math.min(i1, i2)+1);
        }
        return length;
    }
}

No comments:

Post a Comment