using
System;
using
System.Collections.Generic;
class
GFG {
static
bool
IsUpperCase(
char
a)
{
if
(a >=
'A'
&& a <=
'Z'
)
return
true
;
return
false
;
}
static
int
LengthOfResultantString(
string
s,
int
k)
{
Dictionary<
char
,
int
> upper
=
new
Dictionary<
char
,
int
>();
Dictionary<
char
,
int
> lower
=
new
Dictionary<
char
,
int
>();
int
head = 0;
int
tail = 0;
int
invalidSubstringLength = 0;
int
originalLength = s.Length;
for
(head = 0; head < originalLength; head++) {
if
(IsUpperCase(s[head])) {
char
lowerChar = (
char
)(s[head] + 32);
if
(!upper.ContainsKey(lowerChar)) {
upper[lowerChar] = 1;
}
else
{
upper[lowerChar]++;
}
}
else
{
if
(!lower.ContainsKey(s[head])) {
lower[s[head]] = 1;
}
else
{
lower[s[head]]++;
}
}
if
((head - tail + 1) == k) {
if
(DictionaryEquals(upper, lower)) {
invalidSubstringLength
= invalidSubstringLength + k;
tail = head + 1;
upper.Clear();
lower.Clear();
}
else
if
(IsUpperCase(s[tail])) {
char
lowerChar = (
char
)(s[tail] + 32);
if
(upper.ContainsKey(lowerChar)) {
upper[lowerChar]--;
if
(upper[lowerChar] == 0) {
upper.Remove(lowerChar);
}
}
tail++;
}
else
{
if
(lower.ContainsKey(s[tail])) {
lower[s[tail]]--;
if
(lower[s[tail]] == 0) {
lower.Remove(s[tail]);
}
}
tail++;
}
}
}
return
originalLength - invalidSubstringLength;
}
static
bool
DictionaryEquals(Dictionary<
char
,
int
> dict1,
Dictionary<
char
,
int
> dict2)
{
if
(dict1.Count != dict2.Count) {
return
false
;
}
foreach
(
var
kvp
in
dict1)
{
if
(!dict2.TryGetValue(kvp.Key,
out
int
value)
|| value != kvp.Value) {
return
false
;
}
}
return
true
;
}
static
void
Main()
{
string
S =
"xyzAdaD"
;
int
K = 4;
Console.WriteLine(LengthOfResultantString(S, K));
}
}