zoukankan      html  css  js  c++  java
  • [leetcode]159. Longest Substring with At Most Two Distinct Characters至多包含两种字符的最长子串

    Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

    Example 1:

    Input: "eceba"
    Output: 3
    Explanation: t is "ece" which its length is 3.

    Example 2:

    Input: "ccaabbb"
    Output: 5
    Explanation: t is "aabbb" which its length is 5.

    题意:

    给定字符串,找出至多包含两种字符的最长子串。

    思路:

      j          
     “e c e b a”
       i                    e-0
         i                  c-1
             i              e-2
    -------map.size()<= 2
                i           b-3  此时移动 j 

    代码:

     1 class Solution {
     2     public int lengthOfLongestSubstringTwoDistinct(String s) {
     3         if(s.length() < 2) return s.length();
     4         HashMap<Character, Integer> map = new HashMap<>();
     5         int result = 0;
     6         int j = 0;
     7         for(int i = 0; i < s.length(); ){
     8             char c = s.charAt(i);
     9             if(map.size() <= 2){
    10                 map.put(c, i);
    11                 i++;
    12             }
    13             if(map.size() > 2){
    14                 int leftMost = s.length();
    15                 for(int n : map.values()){
    16                     leftMost = Math.min(leftMost, n);
    17                 }
    18                 map.remove(s.charAt(leftMost));
    19                 j = leftMost + 1;   
    20             }
    21             result = Math.max(result, i - j );
    22         }
    23           return result;  
    24     }
    25 }
  • 相关阅读:
    Java的简单书写格式
    注解(Annotation)
    Container(容器)与 Injector(注入)
    maven的下载,安装配置以及build一个java web项目
    Version Control,Git的下载与安装
    URL和URI的区别
    HTTP请求解析过程 (简单概括)
    函数式编程语言(functional language)
    HTTP1.1协议中文版-RFC2616
    练习--str
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201946.html
Copyright © 2011-2022 走看看