Longest Substring with At Most K Distinct Characters

 1 public class Solution {
 2     public int lengthOfLongestSubstringKDistinct(String s, int k) {
 3         if (k == 0) {
 4             return 0;
 5         }
 6         
 7         Map<Character, Integer> letters = new HashMap<>();
 8         int result = 0;
 9         int count = 0;
10         for (int left = 0, right = 0; right < s.length(); right++) {
11             letters.put(s.charAt(right), letters.getOrDefault(s.charAt(right), 0) + 1);
12             if (letters.get(s.charAt(right)) == 1) {
13                 count++;
14             }
15             
16             if (count > k) {
17                 while (left < right && letters.get(s.charAt(left)) > 0) {
18                     int current = letters.get(s.charAt(left));
19                     letters.put(s.charAt(left++), current - 1);
20                     if (current == 1) {
21                         count--;
22                         break;
23                     }
24                 }
25             }
26             
27             result = Math.max(result, right - left + 1);
28         }
29         return result;
30     }
31 }

1. put element do not forget to + 1

2. do not forget left move left++.

转载于:https://www.cnblogs.com/shuashuashua/p/5633045.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值