zoukankan      html  css  js  c++  java
  • LeetCode-Longest Substring with At Most K Distinct Characters

    Given a string, find the length of the longest substring T that contains at most k distinct characters.

    For example, Given s = “eceba” and k = 2,

    T is "ece" which its length is 3.

    Analysis:

    Adding ith char into current substring, keep tracking the number of each char in the current substring, if the distinct number constraint is violated, we move the start forward until the contraint is satisfied.

    Solution:

     1 public class Solution {
     2     public int lengthOfLongestSubstringKDistinct(String s, int k) {
     3         if (s.isEmpty() || k==0) return 0;
     4         
     5         HashMap<Character,Integer> charMap = new HashMap<Character,Integer>();
     6         int start = 0, end = 1, distNum = 1;
     7         charMap.put(s.charAt(0),1);
     8         
     9         int res = 1;
    10         while (end<s.length()){
    11             char cEnd = s.charAt(end);
    12             if (charMap.containsKey(cEnd)){
    13                 charMap.put(cEnd,charMap.get(cEnd)+1);
    14             } else {
    15                 charMap.put(cEnd,1);
    16                 distNum++;
    17                 while (distNum>k){
    18                     char cStart = s.charAt(start);
    19                     int val = charMap.get(cStart)-1;
    20                     if (val==0){
    21                       distNum--;
    22                       charMap.remove(cStart);
    23                     } else charMap.put(cStart,val);
    24                     start++;
    25                 }
    26             }
    27             end++;
    28             res = Math.max(end-start,res);
    29         }
    30         return res;
    31     }
    32 }
  • 相关阅读:
    55.UIbutton点击切换颜色
    54.NSJSONSerialization类进行json解析(字符串“UTF-8解码”)
    53.设置内容的行间距
    第二阶段冲刺7
    第二阶段冲刺6
    第十四周
    第二阶段冲刺5
    第二阶段冲刺4
    第二阶段冲刺3
    第二阶段冲刺2
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5740921.html
Copyright © 2011-2022 走看看