[LeetCode] Find Mirror Score of a String

3412. Find Mirror Score of a String

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:

  • Iterate through the string from left to right.
  • At each index i, find the closest unmarked index j such that j < i and s[j] is the mirror of s[i]. Then, mark both indices i and j, and add the value i - j to the total score.
  • If no such index j exists for the index i, move on to the next index without making any changes.

Return the total score at the end of the process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
long long calculateScore(string s) {
long long res = 0;
vector<vector<int>> st(26);
for(int i = 0; i < s.length(); i++) {
int me = s[i] - 'a', you = 25 - me;
if(st[you].size()) {
res += i - st[you].back(); st[you].pop_back();
} else st[me].push_back(i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/05/PS/LeetCode/find-mirror-score-of-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.