LeetCode in Kotlin

1405. Longest Happy String

Medium

A string s is called happy if it satisfies the following conditions:

Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: a = 1, b = 1, c = 7

Output: “ccaccbcc”

Explanation: “ccbccacc” would also be a correct answer.

Example 2:

Input: a = 7, b = 1, c = 0

Output: “aabaa”

Explanation: It is the only correct answer in this case.

Constraints:

Solution

class Solution {
    fun longestDiverseString(a: Int, b: Int, c: Int): String {
        val sb = StringBuilder()
        val remains = intArrayOf(a, b, c)
        val chars = charArrayOf('a', 'b', 'c')
        var preIndex = -1
        do {
            var index: Int
            var largest: Boolean
            if (preIndex != -1 &&
                remains[preIndex]
                == Math.max(remains[0], Math.max(remains[1], remains[2]))
            ) {
                index = if (preIndex == 0) {
                    if (remains[1] > remains[2]) 1 else 2
                } else if (preIndex == 1) {
                    if (remains[0] > remains[2]) 0 else 2
                } else {
                    if (remains[0] > remains[1]) 0 else 1
                }
                largest = false
            } else {
                index = if (remains[0] > remains[1]) 0 else 1
                index = if (remains[index] > remains[2]) index else 2
                largest = true
            }
            remains[index]--
            sb.append(chars[index])
            if (remains[index] > 0 && largest) {
                remains[index]--
                sb.append(chars[index])
            }
            preIndex = index
        } while (remains[0] + remains[1] + remains[2] != remains[preIndex])
        return sb.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