LeetCode-in-Java

3412. Find Mirror Score of a String

Medium

You are given a string s.

We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a' is 'z', and the mirror of 'y' is 'b'.

Initially, all characters in the string s are unmarked.

You start with a score of 0, and you perform the following process on the string s:

Return the total score at the end of the process.

Example 1:

Input: s = “aczzx”

Output: 5

Explanation:

Example 2:

Input: s = “abcdef”

Output: 0

Explanation:

For each index i, there is no index j that satisfies the conditions.

Constraints:

Solution

import java.util.ArrayList;

@SuppressWarnings("unchecked")
public class Solution {
    public long calculateScore(String s) {
        int n = s.length();
        ArrayList<Integer>[] st = new ArrayList[26];
        long r = 0;
        for (int i = 0; i < 26; i++) {
            st[i] = new ArrayList<>();
        }
        for (int i = 0; i < n; i++) {
            int mc = 'z' - (s.charAt(i) - 'a');
            int p = mc - 'a';
            if (!st[p].isEmpty()) {
                r += i - st[p].remove(st[p].size() - 1);
            } else {
                st[s.charAt(i) - 'a'].add(i);
            }
        }
        return r;
    }
}