-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0424.cpp
More file actions
33 lines (33 loc) · 1.18 KB
/
0424.cpp
File metadata and controls
33 lines (33 loc) · 1.18 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
class Solution {
private:
int getMostFrequentCount(map<char,int> &occurrences) {
int maxOccurrence = 0;
for (char c = 'A'; c <= 'Z'; c++)
maxOccurrence = max(maxOccurrence, occurrences[c]);
return maxOccurrence;
}
public:
int characterReplacement(string s, int k) {
if (!s.length()) return 0;
int start = 0, maxLength = 0;
map<char,int> occurrences;
for (int end = 0; end < s.length(); end++) {
occurrences[s[end]]++;
int mostFrequentCount = getMostFrequentCount(occurrences);
int currentLength = end - start + 1;
int replacements = currentLength - mostFrequentCount;
if (replacements <= k) {
maxLength = max(maxLength, currentLength);
} else {
while (start < end && replacements > k) {
occurrences[s[start]]--;
start++;
currentLength--;
mostFrequentCount = getMostFrequentCount(occurrences);
replacements = currentLength - mostFrequentCount;
}
}
}
return maxLength;
}
};