-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathLongest_Repeating_Character_Replacement.cpp
51 lines (51 loc) · 1.45 KB
/
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
class Solution {
public:
int characterReplacement(string s, int k) {
int n = (int)s.length();
int result = 0;
if(k == 0) {
for(int i = 0; i < n; i++) {
char ch = s[i];
int len = 0; len++;
while(i + 1 < n and s[i + 1] == ch) {
i++; len++;
}
result = max(result, len);
}
return result;
}
for(char ch = 'A'; ch <= 'Z'; ch++) {
string tmp = s;
int start = 0, end = 0;
for(int i = 0, j = k; i < n and j > 0; i++, end++) {
if(tmp[i] != ch) {
tmp[i] = ch;
j--;
}
}
while(end < n and s[end] == ch) {
end++;
}
result = max(result, end - start);
int indx = start;
while(end < n) {
while(indx < end and s[indx] == ch) {
indx++;
}
if(indx < end) {
tmp[indx] = s[indx];
start = ++indx;
}
if(end < n) {
tmp[end] = ch;
end++;
}
while(end < n and s[end] == ch) {
end++;
}
result = max(result, end - start);
}
}
return result;
}
};