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.
1using System;
2using System.Text;
3
4public class Solution {
5 public string StrWithout3a3b(int a, int b) {
6 StringBuilder sb = new StringBuilder();
7 while (a > 0 || b > 0) {
8 bool writeA = false;
9 int n = sb.Length;
10 if (n >= 2 && sb[n-1] == sb[n-2]) {
11 if (sb[n-1] == 'b') writeA = true;
12 } else {
13 if (a >= b) writeA = true;
14 }
15
16 if (writeA) {
17 sb.Append('a');
18 a--;
19 } else {
20 sb.Append('b');
21 b--;
22 }
23 }
24 return sb.ToString();
25 }
26
27 public static void Main() {
28 Solution sol = new Solution();
29 Console.WriteLine(sol.StrWithout3a3b(4, 1));
30 }
31}
This C# solution uses a StringBuilder
to effectively construct the output string. The logic ensures no three continuous 'a' or 'b' are appended by checking recent characters and available counts.
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 C solution follows a clear pattern by interleaving the characters carefully based on their counts. It constructs the string by focusing on avoiding 'aaa' or 'bbb' through interleaving up to two of the more frequent characters with one of the weaker.