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 leetcode
个人分类: String substring问题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭