Skip to main content
  1. Posts/

LeetCode-3412 计算字符串的镜像分数

·1 min·

LeetCode-3412 计算字符串的镜像分数 #

Solution 1 #

分别用栈来维护每个字母当前未标记的位置, 一边遍历一边更新.

代码如下:

class Solution:
    def calculateScore(self, s: str) -> int:
        book = defaultdict(list)
        ans = 0
        for i, ch in enumerate(s):
            m_ch = chr(ord('a') + (ord('z') - ord(ch)))
            if book[m_ch]:
                ans += i - book[m_ch][-1]
                book[m_ch].pop()
            else:
                book[ch].append(i)
        return ans