LeetCode in Kotlin

1542. Find Longest Awesome Substring

Hard

You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.

Return the length of the maximum length awesome substring of s.

Example 1:

Input: s = “3242415”

Output: 5

Explanation: “24241” is the longest awesome substring, we can form the palindrome “24142” with some swaps.

Example 2:

Input: s = “12345678”

Output: 1

Example 3:

Input: s = “213123”

Output: 6

Explanation: “213123” is the longest awesome substring, we can form the palindrome “231132” with some swaps.

Constraints:

Solution

class Solution {
    fun longestAwesome(s: String): Int {
        val n = s.length
        val idx = IntArray(Math.pow(2.0, 10.0).toInt())
        idx.fill(Int.MAX_VALUE)
        idx[0] = -1
        var mask = 0
        var ans = 0
        for (i in 0 until n) {
            mask = mask xor (1 shl s[i].code - '0'.code)
            ans = Math.max(ans, i - idx[mask])
            for (j in 0..9) {
                ans = Math.max(ans, i - idx[mask xor (1 shl j)])
            }
            idx[mask] = Math.min(idx[mask], i)
        }
        return ans
    }
}