首页 > 代码库 > 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.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。