Leetcode 340: 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.

 

 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 }

 

posted @ 2017-12-28 13:37  逸朵  阅读(131)  评论(0)    收藏  举报