Leetcode 340: Longest Substring with At Most K Distinct Characters

最长含k不同字符子串
本文介绍了一种算法,用于寻找给定字符串中最长的包含最多k个不同字符的子串长度。通过使用字典记录字符及其位置,并在遍历过程中动态调整窗口大小来实现。适用于需要解决特定字符限制问题的场景。

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.

 

 1 public class Solution {
 2     public int LengthOfLongestSubstringKDistinct(string s, int k) {
 3         if (s == null || k == 0) return 0;
 4         if (s.Length <= k) return s.Length;
 5         
 6         var dict = new Dictionary<char, int>();
 7         int start = 0, max = 0;
 8         for (int i = 0; i < s.Length; i++)
 9         {
10             dict[s[i]] = i;
11             
12             if (dict.Count <= k)
13             {
14                 max = Math.Max(max, i - start + 1);
15             }
16             else
17             {
18                 int lastIndex = Int32.MaxValue;
19                 
20                 for (int j = start; j < i; j++)
21                 {
22                     if (dict[s[j]] < lastIndex)
23                     {
24                         lastIndex = dict[s[j]]; 
25                     }
26                 }
27                 
28                 dict.Remove(s[lastIndex]);
29                 start = lastIndex + 1;
30             }
31         }
32         
33         return max;
34     }
35 }

 

转载于:https://www.cnblogs.com/liangmou/p/8135264.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值