Leetcode Everyday: 340. Longest Substring with At Most K Distinct Characters
来源:互联网 发布:程序员英语软件 编辑:程序博客网 时间:2024/04/29 18:15
https://leetcode.com/problems/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
public class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { if(k==0) return 0; char[] cArr = s.toCharArray(); int[] occ = new int[128]; int start = 0; int dis = 0; int maxLen = 0; for(int i = 0; i<cArr.length; i++){ if(occ[cArr[i]]==0){ occ[cArr[i]]++;dis++; if(dis>k){ while(--occ[cArr[start++]] != 0); } }else{ occ[cArr[i]]++; } if(i-start+1>maxLen) maxLen = i-start+1; } return maxLen; }}The idea is to keep a sliding window using two pointers. The first pointer is start, and the second pointer is i. we record how many times does a char occurs in the window. When we encounter a new char and there are k+1 chars in the window, we increase the start pointer and make correspond changes in the occurrence array, util we find some chars occurrence is from 1->0, this means a char has been removed out of the window.
asd
0 0
- Leetcode Everyday: 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 Longest Substring with At Most K Distinct Characters
- Leetcode 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 解题报告
- lintcode:Longest Substring with At Most K Distinct Characters
- Longest Substring with At Most K Distinct Characters
- Longest Substring with At Most K Distinct Characters
- [Amazon] 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
- [Leetcode]Longest Substring with At Most Two Distinct Characters
- LeetCode - Longest Substring with At Most Two Distinct Characters
- Leetcode: Longest Substring with At Most Two Distinct Characters
- Windows下的systeminfo命令获取系统信息
- 【C/C++】:sizeof详解
- TortoiseSVN下载,安装,配置
- onSaveInstanceState和onRestoreInstanceState 触发时机
- asp.net中Cookie的使用
- Leetcode Everyday: 340. Longest Substring with At Most K Distinct Characters
- 如何计算时间复杂度
- 基于FS4412嵌入式系统移植(1) 基本环境搭建
- HDU2191(多重背包)
- Java实现导出Excel文件
- Java文件读写操作
- UVA 10036 Divisibility
- Android学习笔记:高效载入大量Bitmap
- ListView