LeetCode 340. Longest Substring with At Most K Distinct Characters
原题链接在这里: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.
题解:
类似Longest Substring with At Most Two Distinct Characters.
2变成k即可.
Time Complexity: O(n), n = s.length(). Space: O(1), map size.
AC Java:
1 public class Solution { 2 public int lengthOfLongestSubstringKDistinct(String s, int k) { 3 int res = 0; 4 int [] map = new int[256]; 5 int walker = 0; 6 int runner = 0; 7 int count = 0; 8 while(runner < s.length()){ 9 if(map[s.charAt(runner++)]++ == 0){ 10 count++; 11 } 12 while(count > k){ 13 if(map[s.charAt(walker++)]-- == 1){ 14 count--; 15 } 16 } 17 res = Math.max(res, runner - walker); 18 } 19 return res; 20 } 21 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步