LeetCode-in-Java

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

import java.util.Arrays;

public class Solution {
    public long appealSum(String s) {
        int len = s.length();
        int[] lastPos = new int[26];
        Arrays.fill(lastPos, -1);
        long res = 0;
        for (int i = 0; i < len; i++) {
            int idx = s.charAt(i) - 'a';
            res += (long) (i - lastPos[idx]) * (len - i);
            lastPos[idx] = i;
        }
        return res;
    }
}