LeetCode 984: String Without AAA or BBB Solution

Master LeetCode problem 984 (String Without AAA or BBB), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

984. String Without AAA or BBB

Problem Explanation

Explanation:

To solve this problem, we need to construct a string of length a + b such that it contains exactly a 'a' characters and b 'b' characters without having the substrings 'aaa' or 'bbb'.

One approach to solve this problem is as follows:

  1. Start by creating an empty result string.
  2. While a or b is greater than zero:
    • If a is greater than b, add 'a' to the result string and decrement a.
    • Otherwise, add 'b' to the result string and decrement b.
    • If the last two characters in the result string are 'aa', add 'b' to avoid 'aaa'.
    • If the last two characters in the result string are 'bb', add 'a' to avoid 'bbb'.

This process will ensure that we construct a valid string meeting the requirements.

Solution Code

class Solution {
    public String strWithout3a3b(int a, int b) {
        StringBuilder sb = new StringBuilder();
        while (a > 0 || b > 0) {
            if (a > b) {
                sb.append("a");
                a--;
            } else if (b > a) {
                sb.append("b");
                b--;
            }
            if (sb.length() >= 2 && sb.charAt(sb.length() - 1) == sb.charAt(sb.length() - 2)) {
                if (sb.charAt(sb.length() - 1) == 'a') {
                    sb.append("b");
                    b--;
                } else {
                    sb.append("a");
                    a--;
                }
            }
        }
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 984 (String Without AAA or BBB)?

This page provides optimized solutions for LeetCode problem 984 (String Without AAA or BBB) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 984 (String Without AAA or BBB)?

The time complexity for LeetCode 984 (String Without AAA or BBB) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 984 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 984 in Java, C++, or Python.

Back to LeetCode Solutions