[translate by ChatGPT] This problem was fairly easy and intuitive. I maintained a deque of indices for each character, and while scanning the string, I searched for the most recent occurrence of its mirror character.

During the process, I made a small mistake: I accidentally wrote pop_front instead of pop_back. But I caught that bug quickly.

Code

class Solution {
public:
    long long calculateScore(string s) {
        vector<deque<int>> front(26,deque<int>()); // the last index for a char
        long long score = 0;
        for(int i = 0 ; i < s.size() ; ++i) {
            const char c = s[i];
            deque<int>& lastMirror = front[25-int(c-'a')];
            if (lastMirror.size() != 0) {
                int nearest = lastMirror.back();
                score += (i - nearest);
                lastMirror.pop_back();
            } else {
                front[int(c-'a')].push_back(i);
            }
        }
        return score;
    }
};

Code: Rewrite in 2026-02-08

class Solution {
public:
    long long calculateScore(string s) {
        vector<stack<int>> v(26); // char(int) -> idx

        int n = s.size();
        long long score = 0;
        for(int i = 0 ; i < n ; ++i) {
            int id = s[i] - 'a';
            int rId = 25 - id;
            
            if(v[rId].size() != 0) {
                int prevId = v[rId].top();
                v[rId].pop();
                score += (i - prevId);
            } else {
                v[id].push(i);
            }
        }

        return score;
    }
};