首页 > 代码库 > Leetcode-Longest Substring with At Most Two Distinct Characters.

Leetcode-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.

Solution:

 1 public class Solution { 2     public int lengthOfLongestSubstringTwoDistinct(String s) { 3         //Two pointers: start, end. Maintain that start-end is a valid substring. 4         //Record the number of the two chars in start-end. 5         //Inc end, if the charAt(end) is a thrid char, then inc start, until the start-end is a valid substring again 6         //record the length of the new string. 7  8         Map<Character,Integer> charNum = new HashMap<Character,Integer>(); 9         int start = 0;10         int end = 0;11         int charType = 2;12         int maxLen = 0;13         while (end<s.length()){14             char cur = s.charAt(end);15             //if this char is in substring already, then increase its number16             if (charNum.containsKey(cur))17                 charNum.put(cur,charNum.get(cur)+1);18             else {19                 charNum.put(cur,1);20                 if (charType>0) charType--;21                 else {22                    //We need eliminate another char in substring to maintain the feasibility of the substring.23                    while (charNum.get(s.charAt(start))>1){24                        charNum.put(s.charAt(start),charNum.get(s.charAt(start))-1);25                        start++;26                    }27                    charNum.remove(s.charAt(start));28                    start++;29                 }30             }31 32             if (maxLen<end-start+1) maxLen = end-start+1;33             end++;34         }35 36         return maxLen;        37     }38 }

 

Leetcode-Longest Substring with At Most Two Distinct Characters.