LeetCode in Kotlin

3438. Find Valid Pair of Adjacent Digits in String

Easy

You are given a string s consisting only of digits. A valid pair is defined as two adjacent digits in s such that:

Return the first valid pair found in the string s when traversing from left to right. If no valid pair exists, return an empty string.

Example 1:

Input: s = “2523533”

Output: “23”

Explanation:

Digit '2' appears 2 times and digit '3' appears 3 times. Each digit in the pair "23" appears in s exactly as many times as its numeric value. Hence, the output is "23".

Example 2:

Input: s = “221”

Output: “21”

Explanation:

Digit '2' appears 2 times and digit '1' appears 1 time. Hence, the output is "21".

Example 3:

Input: s = “22”

Output: “”

Explanation:

There are no valid adjacent pairs.

Constraints:

Solution

class Solution {
    fun findValidPair(s: String): String {
        val t = IntArray(26)
        for (i in 0..<s.length) {
            t[s[i].code - '0'.code]++
        }
        for (i in 1..<s.length) {
            if (s[i - 1] == s[i] || t[s[i - 1].code - '0'.code] != s[i - 1].code - '0'.code ||
                t[s[i].code - '0'.code] != s[i].code - '0'.code
            ) {
                continue
            }
            return s.substring(i - 1, i + 1)
        }
        return ""
    }
}