Skip to content

Commit 844b196

Browse files
authored
Create longest-repeating-character-replacement.cpp
1 parent a0a5664 commit 844b196

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O()
3+
4+
class Solution {
5+
public:
6+
int characterReplacement(string s, int k) {
7+
vector<int> cache(26);
8+
9+
int i = 0, j = 0, times = k, res = 0;
10+
for (; j < s.size(); ++j) {
11+
++cache[s[j] - 'A'];
12+
if (s[j] != s[i]) {
13+
--times;
14+
if (times < 0) {
15+
res = max(res, j - i);
16+
while (i < j && k - (j - i + 1 - cache[s[i] - 'A']) < 0) {
17+
--cache[s[i++] - 'A'];
18+
}
19+
times = k - (j - i + 1 - cache[s[i] - 'A']);
20+
}
21+
}
22+
}
23+
return max(res, j - i + min(i, times));
24+
}
25+
};

0 commit comments

Comments
 (0)