欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

159. Longest Substring with At Most Two Distinct Characters,longestsubstring

来源: javaer 分享于  点击 19405 次 点评:82

159. Longest Substring with At Most Two Distinct Characters,longestsubstring


题目描述

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.

思路分析

这题依旧是滑动窗口的思想
要求找到最长的只含两个不同元素的子串

代码

public int lengthOfLongestSubstringTwoDistinct(String s)
    {   
        int[] map = new int[256];
        int counter=0, begin=0, end=0, d=0; 
        while(end<s.length()){
            if(map[s.charAt(end++)]++>0) counter++; 
            while(counter>0) if(map[s.charAt(begin++)]-->1) counter--;
            d=Math.max(d, end-begin); //while valid, update d
        }
        return d;
    }

相关文章

    暂无相关文章

用户点评