LeetCode in Kotlin

767. Reorganize String

Medium

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" if not possible.

Example 1:

Input: s = “aab”

Output: “aba”

Example 2:

Input: s = “aaab”

Output: “”

Constraints:

Solution

class Solution {
    fun reorganizeString(s: String): String {
        val hash = IntArray(26)
        for (element in s) {
            hash[element.code - 'a'.code]++
        }
        var max = 0
        var letter = 0
        for (i in hash.indices) {
            if (hash[i] > max) {
                max = hash[i]
                letter = i
            }
        }
        if (max > (s.length + 1) / 2) {
            return ""
        }
        val res = CharArray(s.length)
        var idx = 0
        while (hash[letter] > 0) {
            res[idx] = (letter + 'a'.code).toChar()
            idx += 2
            hash[letter]--
        }
        for (i in hash.indices) {
            while (hash[i] > 0) {
                if (idx >= res.size) {
                    idx = 1
                }
                res[idx] = (i + 'a'.code).toChar()
                idx += 2
                hash[i]--
            }
        }
        return String(res)
    }
}
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