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 }
  • 相关阅读:
    ZOJ4125 Sekiro
    ZOJ4118 Stones in the Bucket
    ZOJ4115 Wandering Robot
    ZOJ4113 Calandar
    【递归】N皇后问题 和 2n皇后问题 dfs
    7-18
    7_13
    二维前缀和
    64位整数乘法
    【分治】魔法石的诱惑
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201946.html
Copyright © 2011-2022 走看看