码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring with At Most K Distinct Characters

时间:2016-08-03 01:34:19      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains k unique character is "bcbbbbcccb".

分析:

用hashmap记录每个character从start到当前位置出现的次数,如果第k + 1个character出现, 更新maxLength,我们需要把左边的pointer(start) 往右移,直到从start到current之间只有K个character.

 1 public class Solution {
 2     public int lengthOfLongestSubstringKDistinct(String s, int k) {
 3         if (k == 0 || s == null || s.length() == 0) return 0;
 4         if (s.length() <= k) return s.length();
 5 
 6         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 7 
 8         int maxLen = k;
 9         int start = 0;
10         for (int i = 0; i < s.length(); i++) {
11             char c = s.charAt(i);
12             map.put(c, map.getOrDefault(c, 0) + 1);
13             if (map.size() > k) {
14                 maxLen = Math.max(maxLen, i - start);
15                 while (map.size() > k) {
16                     char preCh = s.charAt(start);
17                     if (map.get(preCh) == 1) {
18                         map.remove(preCh);
19                     } else {
20                         map.put(preCh, map.get(preCh) - 1);
21                     }
22                     start++;
23                 }
24             }
25         }
26         maxLen = Math.max(maxLen, s.length() - start);
27         return maxLen;
28     }
29 }

 

Longest Substring with At Most K Distinct Characters

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5731307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!