zoukankan      html  css  js  c++  java
  • 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 number
    16             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 }
  • 相关阅读:
    IT程序猿”是怎样练成的? 之 提升内驱力的7大秘籍转
    wp7 退出程序的提示对话框
    生活不容易
    Decorator模式学习
    用序列化方法实现的Prototype的深拷贝
    Observer pettern
    Adapter模式学习
    bridge模式学习
    Composite模式学习
    Prototype原形设计模式
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4160854.html
Copyright © 2011-2022 走看看