LeetCode in Kotlin

984. String Without AAA or BBB

Medium

Given two integers a and b, return any string s such that:

Example 1:

Input: a = 1, b = 2

Output: “abb”

Explanation: “abb”, “bab” and “bba” are all correct answers.

Example 2:

Input: a = 4, b = 1

Output: “aabaa”

Constraints:

Solution

class Solution {
    fun strWithout3a3b(a: Int, b: Int): String {
        val first = if (a > b) "a" else "b"
        val second = if (first == "a") "b" else "a"
        var firstLen = a.coerceAtLeast(b)
        var secondLen = a.coerceAtMost(b)
        val ans = StringBuilder()
        // Case 1 : A and B count are unequal.
        while (firstLen > 0 && secondLen > 0 && firstLen != secondLen) {
            ans.append(first)
            ans.append(first)
            firstLen = firstLen - 2
            ans.append(second)
            secondLen--
        }
        // Case 2: A and B count are equal
        while (firstLen > 0 && secondLen > 0) {
            ans.append(first)
            ans.append(second)
            firstLen--
            secondLen--
        }
        // left over, just append
        while (firstLen > 0) {
            ans.append(first)
            firstLen--
        }
        return ans.toString()
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy