Longest Substring with At Most K Distinct Characters
来源:互联网 发布:centos如何安装ssh 编辑:程序博客网 时间:2024/05/16 07:10
这道题要求给定一个字符串,然后一个k,求一个最大子串的不重复的字符不大于k的最大子串长度
分析:这道题本质要维护一个窗口,即要维护一个hashmap,key为字符,value为窗口内的该字符的个数,然后在窗口扩张过程中,检查chars[end]是否被包含在map中,或者map的大小是否小于k,如果是直接添加;否则就要转为收缩,即start开始收缩,直到到达合适位置
public class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { HashMap<Character,Integer> maps = new HashMap<>(); char[] chars = s.toCharArray(); if(k >= chars.length) return chars.length; int start = 0,end = k-1; int length = end-start; for(int i = 0;i<k;i++){ if(!maps.containsKey(chars[i])) maps.put(chars[i],0); maps.replace(chars[i],maps.get(chars[i])+1); } for(int i = k;i<chars.length;i++){ if(maps.size()<k || maps.containsKey(chars[i])){ if(!maps.containsKey(chars[i])){ maps.put(chars[i],0); } maps.replace(chars[i],maps.get(chars[i])+1); if(++end - start > length) length = end - start; }else{//start remove while(maps.size() == k && start <= end){ int count = maps.get(chars[start]) - 1; if(count == 0){ maps.remove(chars[start]); }else{ maps.replace(chars[start],count); } start++; } if(start <= end){ maps.put(chars[i],1); end = i; } } } return length+1; }}
0 0
- lintcode:Longest Substring with At Most K Distinct Characters
- Longest Substring with At Most K Distinct Characters
- LeetCode 340. Longest Substring with At Most K Distinct Characters
- leetcode Longest Substring with At Most K Distinct Characters
- Longest Substring with At Most K Distinct Characters
- Leetcode Longest Substring with At Most K Distinct Characters
- [Amazon] Longest Substring with At Most K Distinct Characters
- leetcode 340. Longest Substring with At Most K Distinct Characters
- [leetcode] 340. Longest Substring with At Most K Distinct Characters 解题报告
- LeetCode 340. Longest Substring with At Most K Distinct Characters(最长字串)
- Leetcode Everyday: 340. Longest Substring with At Most K Distinct Characters
- Leetcode 159 & 340 Longest Substring with At Most Two/K Distinct Characters
- [Leetcode] 340. Longest Substring with At Most K Distinct Characters 解题报告
- [Leetcode] Longest Substring with At Most Two Distinct Characters
- Leetcode Longest Substring with At Most Two Distinct Characters
- leetcode 159: Longest Substring with At Most Two Distinct Characters
- Longest Substring with At Most Two Distinct Characters
- [Leetcode]Longest Substring with At Most Two Distinct Characters
- 组合数学训练 (16.03.29)
- C语言单链表的创建,插入,删除,逆致
- 深入理解 Java 虚拟机-Java 语法糖
- 面试中遇到的SQL题目
- 50个经典常用的sql语句
- Longest Substring with At Most K Distinct Characters
- 五种Button监听方式总结
- npm介绍
- HttpUtils
- JS编写冒泡排序法和二分查找
- Bear and Polynomials 639 C
- 设计模式:组合模式(Composite)
- 先根递归建立二叉树(顺序表示法)
- yii2分页