Sponsored
Sponsored
This approach constructs the string by always choosing the majority character until we need to switch to prevent three consecutive characters.
Steps:
Time Complexity: O(a + b) because each character is processed once.
Space Complexity: O(a + b) for the result string.
1def strWithout3a3b(a: int, b: int) -> str:
2 res = []
3 while a > 0 or b > 0:
4 writeA = False
5 if len(res) >= 2 and res[-1] == res[-2]:
6 if res[-1] == 'b':
7 writeA = True
8 else:
9 if a >= b:
10 writeA = True
11
12 if writeA:
13 res.append('a')
14 a -= 1
15 else:
16 res.append('b')
17 b -= 1
18 return ''.join(res)
19
20# Example usage
21print(strWithout3a3b(4, 1))
The Python solution builds the string using a list (for efficient append operations) and later converts it to a string. The choice of appending 'a' or 'b' is managed to avoid three consecutive identical characters and to balance the quantity.
This approach leverages an interleaving strategy to distribute characters evenly and avoid consecutive identical sequences.
Steps:
Time Complexity: O(a + b) due to iteration through characters.
Space Complexity: O(a + b) used for the output string.
This Java solution focuses on concatenating strings using a StringBuilder
, where it carefully alternates the occurrence of 'a's and 'b's to avoid triple consecutive occurrences by checking the character counts.