forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0340-LongestSubstringWithAtMostKDistinctCharacters.cs
More file actions
38 lines (34 loc) · 1.14 KB
/
0340-LongestSubstringWithAtMostKDistinctCharacters.cs
File metadata and controls
38 lines (34 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 22.6 MB
// Link: https://leetcode.com/submissions/detail/373794812/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _0340_LongestSubstringWithAtMostKDistinctCharacters
{
public int LengthOfLongestSubstringKDistinct(string s, int k)
{
var counts = new Dictionary<char, int>();
int left = 0, right = 0, maxLength = 0;
while (right < s.Length)
{
if (counts.ContainsKey(s[right]))
counts[s[right]]++;
else
counts[s[right]] = 1;
while (counts.Count > k)
{
counts[s[left]]--;
if (counts[s[left]] == 0) counts.Remove(s[left]);
left++;
}
maxLength = Math.Max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
}
}