日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 340. Longest Substring with At Most K Distinct Characters

發布時間:2025/3/21 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 }

跟上Longest Repeating Character Replacement.

轉載于:https://www.cnblogs.com/Dylan-Java-NYC/p/6384945.html

總結

以上是生活随笔為你收集整理的LeetCode 340. Longest Substring with At Most K Distinct Characters的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。