-
Notifications
You must be signed in to change notification settings - Fork 110
/
424. Longest Repeating Character Replacement.cpp
52 lines (42 loc) · 1.64 KB
/
424. Longest Repeating Character Replacement.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//Runtime: 16 ms, faster than 53.88% of C++ online submissions for Longest Repeating Character Replacement.
//Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Longest Repeating Character Replacement.
class Solution {
public:
int characterReplacement(string s, int k) {
int N = s.size();
int ans = 0;
// for(int i = 0; i < 26; i++){
// lengths[i+'A'] = 0;
// used[i+'A'] = 0;
// }
for(int i = 0; i < 26; i++){
int length = 0;
int used = 0;
int left = 0, right = 0;
char c = 'A' + i;
//skip the character not in s
if(s.find(c) == string::npos)
continue;
// cout << c << endl;
while(right < N){
if(left > 0 && s[left-1] != c){
used--;
}
// cout << "[" << left << ", " << right << "), used: " << used << endl;
while(right < N && (s[right] == c || used < k)){
if(s[right] != c){
used++;
}
right++;
// cout << "[" << left << ", " << right << "), used: " << used << endl;
}
length = max(length, right-left);
// cout << "[" << left << ", " << right << "), length: " << length << ", used: " << used << endl;
left++;
}
ans = max(length, ans);
// cout << "ans: " << ans << endl;
}
return ans;
}
};