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.
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.