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 }
  • 相关阅读:
    node递归批量重命名指定文件夹下的文件
    nvm
    node在Web中的用途
    给flash续命(rtmp/http-flv网页播放器)
    AMR/PCM格式语音采集/编码/转码/解码/播放
    视频分析,目标跟踪应用方案梳理
    srs-librtmp pusher(push h264 raw)
    srs
    nginx-rtmp/http-flv
    Introduction to Sound Programming with ALSA
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4160854.html
Copyright © 2011-2022 走看看