LeetCode in Kotlin

1763. Longest Nice Substring

Easy

A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not.

Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.

Example 1:

Input: s = “YazaAay”

Output: “aAa”

Explanation: “aAa” is a nice string because ‘A/a’ is the only letter of the alphabet in s, and both ‘A’ and ‘a’ appear. “aAa” is the longest nice substring.

Example 2:

Input: s = “Bb”

Output: “Bb”

Explanation: “Bb” is a nice string because both ‘B’ and ‘b’ appear. The whole string is a substring.

Example 3:

Input: s = “c”

Output: “”

Explanation: There are no nice substrings.

Constraints:

Solution

class Solution {
    fun longestNiceSubstring(s: String): String {
        val index = isNotNiceString(s)
        if (index == -1) {
            return s
        }
        val left = longestNiceSubstring(s.substring(0, index))
        val right = longestNiceSubstring(s.substring(index + 1))
        return if (left.length >= right.length) left else right
    }

    private fun isNotNiceString(s: String): Int {
        val set: MutableSet<Char> = HashSet()
        for (c in s.toCharArray()) {
            set.add(c)
        }
        for (i in 0 until s.length) {
            val c = s[i]
            if (!set.contains(c.lowercaseChar()) ||
                !set.contains(c.uppercaseChar())
            ) {
                return i
            }
        }
        return -1
    }
}