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 }
  • 相关阅读:
    vue用户登录状态判断
    Android webView包装WebAPP
    浮动粒子制作404动画页面
    使用 typescript 和 canvas 重构snow效果
    毕达哥拉斯树(pythagorasTree)原理解析及canvas动画实现
    canvas入门之时钟的实现
    canvas动画之动态绘出六边形
    分享一篇vue项目规范
    css3 ajax加载进度线
    react 体验 react与vue的比较
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4160854.html
Copyright © 2011-2022 走看看