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
| class Solution:
def maxRepOpt1(self, text: str) -> int:
idx = [[] for _ in range(26)]
res = 1
# Store indices of each character in idx
for i in range(len(text)):
idx[ord(text[i]) - ord('a')].append(i)
# Iterate through all characters from 'a' to 'z'
for n in range(26):
cnt = 1
cnt1 = 0
mx = 0
for i in range(1, len(idx[n])):
if idx[n][i] == idx[n][i - 1] + 1:
cnt += 1
else:
cnt1 = cnt if idx[n][i] == idx[n][i - 1] + 2 else 0
cnt = 1
mx = max(mx, cnt1 + cnt)
res = max(res, mx + (1 if len(idx[n]) > mx else 0))
return res
|