2
def maxRepOpt1(self, text: str) -> int:5
for char, group in groupby(text):6
group_len = len(list(group))7
char_groups.append((char, group_len))9
char_count = Counter(text)11
longest_substr_len = 1 # Each char itself is substring of len 113
# Scenario-1: Get the longest substr length by just adding one more char to each group14
for char, group_len in char_groups:15
# NOTE: If the total count of the char across full string is < group_len+1,16
# make sure to take the total count only18
# It means we don't have any extra char occurrence which we can add to the current group20
group_len_w_one_addition = min(group_len + 1, char_count[char])21
longest_substr_len = max(longest_substr_len, group_len_w_one_addition)24
# If there are two groups of same char, separated by a group of different char with length=1:25
# 1) We can either swap that one char in the middle with the same char as those two groups27
# - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index28
# - So after swapping, it will become 'aaa a aaa c b'29
# - hence longest substr len of same char 'a' = 731
# 2) We can merge the two groups33
# -> here there are two groups of char 'a' with len = 3 each.34
# -> they are separated by a group of char 'b' with len = 135
# -> hence, we can merge both groups of char 'a' - so that longest substr len = 636
# -> basically, swap the 'b' with 'a' at very last index37
# -> the final string will look like 'aaaaaa b'39
# We will take max length we can get from above two options.41
# Since we need to check the group prior to curr_idx "i" and also next to curr_idx "i";42
# we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive44
for i in range(1, len(char_groups) - 1):45
prev_group_char, prev_group_len = char_groups[i - 1]46
curr_group_char, curr_group_len = char_groups[i]47
next_group_char, next_group_len = char_groups[i + 1]49
if curr_group_len != 1 or prev_group_char != next_group_char:52
len_after_swapping = min(53
prev_group_len + next_group_len + 1, char_count[next_group_char]55
longest_substr_len = max(longest_substr_len, len_after_swapping)57
return longest_substr_len