3634. Find Mirror Score Of A String¶
3634. 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:
- Iterate through the string from left to right.
- At each index
i, find the closest unmarked indexjsuch thatj < iands[j]is the mirror ofs[i]. Then, mark both indicesiandj, and add the valuei - jto the total score. - If no such index
jexists for the indexi, move on to the next index without making any changes.
Return the total score at the end of the process.
Example 1:
Input: s = "aczzx"
Output: 5
Explanation:
i = 0. There is no indexjthat satisfies the conditions, so we skip.i = 1. There is no indexjthat satisfies the conditions, so we skip.i = 2. The closest indexjthat satisfies the conditions isj = 0, so we mark both indices 0 and 2, and then add2 - 0 = 2to the score.i = 3. There is no indexjthat satisfies the conditions, so we skip.i = 4. The closest indexjthat satisfies the conditions isj = 1, so we mark both indices 1 and 4, and then add4 - 1 = 3to the score.
Example 2:
Input: s = "abcdef"
Output: 0
Explanation:
For each index i, there is no index j that satisfies the conditions.
Constraints:
1 <= s.length <= 105sconsists only of lowercase English letters.
Solution¶
class Solution {
public long calculateScore(String s) {
int n = s.length();
long ans = 0;
Map<Integer, List<Integer>> mp = new HashMap<>();
for(int i = 0; i < s.length(); ++i){
int cur = s.charAt(i) - 'a';
int mirror = 25 - cur;
if(mp.containsKey(mirror) && mp.get(mirror).size() > 0){
ans += (long)i - (long)mp.get(mirror).get(mp.get(mirror).size() - 1);
mp.get(mirror).remove(mp.get(mirror).size() - 1);
}
else mp.computeIfAbsent(cur, key -> new ArrayList<>()).add(i);
}
return ans;
}
}
Complexity Analysis¶
- Time Complexity: O(?)
- Space Complexity: O(?)
Explanation¶
[Add detailed explanation here]