LeetCode in Kotlin

2262. Total Appeal of A String

Hard

The appeal of a string is the number of distinct characters found in the string.

Given a string s, return the total appeal of all of its **substrings.**

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

Example 1:

Input: s = “abbca”

Output: 28

Explanation: The following are the substrings of “abbca”:

The total sum is 5 + 7 + 7 + 6 + 3 = 28.

Example 2:

Input: s = “code”

Output: 20

Explanation: The following are the substrings of “code”:

The total sum is 4 + 6 + 6 + 4 = 20.

Constraints:

Solution

class Solution {
    fun appealSum(s: String): Long {
        val len = s.length
        val lastPos = IntArray(26)
        lastPos.fill(-1)
        var res: Long = 0
        for (i in 0 until len) {
            val idx = s[i].code - 'a'.code
            res += ((i - lastPos[idx]) * (len - i)).toLong()
            lastPos[idx] = i
        }
        return res
    }
}