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.
1public class StringWithoutAAAorBBB {
2 public static String strWithout3a3b(int a, int b) {
3 StringBuilder res = new StringBuilder();
4 while (a > 0 || b > 0) {
5 boolean writeA = false;
6 int n = res.length();
7 if (n >= 2 && res.charAt(n-1) == res.charAt(n-2)) {
8 if (res.charAt(n-1) == 'b') writeA = true;
9 } else {
10 if (a >= b) writeA = true;
11 }
12
13 if (writeA) {
14 res.append('a');
15 a--;
16 } else {
17 res.append('b');
18 b--;
19 }
20 }
21 return res.toString();
22 }
23
24 public static void main(String[] args) {
25 int a = 4, b = 1;
26 System.out.println(strWithout3a3b(a, b));
27 }
28}
This Java solution utilizes a StringBuilder
to dynamically form the desired output string while ensuring no 'aaa' or 'bbb' substring exists. The choice of character is based on existing counts and recent characters added.
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.