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.
using System.Text;
public class Solution {
public string StrWithout3a3b(int a, int b) {
StringBuilder result = new StringBuilder();
while (a > 0 || b > 0) {
if (a > b) {
if (a > 0) { result.Append('a'); a--; }
if (a > 0) { result.Append('a'); a--; }
if (b > 0) { result.Append('b'); b--; }
} else {
if (b > 0) { result.Append('b'); b--; }
if (b > 0) { result.Append('b'); b--; }
if (a > 0) { result.Append('a'); a--; }
}
}
return result.ToString();
}
public static void Main() {
Solution sol = new Solution();
Console.WriteLine(sol.StrWithout3a3b(4, 1));
}
}
This C# solution applies a structured pattern that systematically processes the counts of 'a' and 'b', ensuring that their interleave does not form consecutive sequences of more than two 'a's or 'b's.