LeetCode 题解工作台
计算字符串的镜像分数
给你一个字符串 s 。 英文字母中每个字母的 镜像 定义为反转字母表之后对应位置上的字母。例如, 'a' 的镜像是 'z' , 'y' 的镜像是 'b' 。 最初,字符串 s 中的所有字符都 未标记 。 字符串 s 的初始分数为 0 ,你需要对其执行以下过程: 从左到右遍历字符串。 对于每个下标 i…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
我们可以用一个哈希表 来存储每个未标记的字符的下标列表,其中键是字符,值是下标列表。 我们遍历字符串 ,对于每个字符 ,我们找到其镜像字符 ,如果 中存在 ,我们就取出 对应的下标列表 ,取出 的最后一个元素 ,并将 从 中移除。如果 变为空,我们就将 从 中移除。此时,我们就找到了一个满足条件的下标对 $(\textit{j}, \textit{i})$,并将 $\textit…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你一个字符串 s。
英文字母中每个字母的 镜像 定义为反转字母表之后对应位置上的字母。例如,'a' 的镜像是 'z','y' 的镜像是 'b'。
最初,字符串 s 中的所有字符都 未标记 。
字符串 s 的初始分数为 0 ,你需要对其执行以下过程:
- 从左到右遍历字符串。
- 对于每个下标
i,找到距离最近的 未标记 下标j,下标j需要满足j < i且s[j]是s[i]的镜像。然后 标记 下标i和j,总分加上i - j的值。 - 如果对于下标
i,不存在满足条件的下标j,则跳过该下标,继续处理下一个下标,不需要进行标记。
返回最终的总分。
示例 1:
输入: s = "aczzx"
输出: 5
解释:
i = 0。没有符合条件的下标j,跳过。i = 1。没有符合条件的下标j,跳过。i = 2。距离最近的符合条件的下标是j = 0,因此标记下标 0 和 2,然后将总分加上2 - 0 = 2。i = 3。没有符合条件的下标j,跳过。i = 4。距离最近的符合条件的下标是j = 1,因此标记下标 1 和 4,然后将总分加上4 - 1 = 3。
示例 2:
输入: s = "abcdef"
输出: 0
解释:
对于每个下标 i,都不存在满足条件的下标 j。
提示:
1 <= s.length <= 105s仅由小写英文字母组成。
解题思路
方法一:哈希表
我们可以用一个哈希表 来存储每个未标记的字符的下标列表,其中键是字符,值是下标列表。
我们遍历字符串 ,对于每个字符 ,我们找到其镜像字符 ,如果 中存在 ,我们就取出 对应的下标列表 ,取出 的最后一个元素 ,并将 从 中移除。如果 变为空,我们就将 从 中移除。此时,我们就找到了一个满足条件的下标对 ,并将 加到答案中。否则,我们将 加入到 中。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def calculateScore(self, s: str) -> int:
d = defaultdict(list)
ans = 0
for i, x in enumerate(s):
y = chr(ord("a") + ord("z") - ord(x))
if d[y]:
j = d[y].pop()
ans += i - j
else:
d[x].append(i)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for n = s.length due to the single-pass iteration and constant-time stack operations. Space complexity is O(1) relative to input size because only 26 stacks for lowercase letters are maintained. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on the stack-based state management pattern for mirror matching.
- question_mark
Ask about handling unmarked letters and simultaneous updates to stacks.
- question_mark
Probe edge cases with repeated letters or no mirror pairs.
常见陷阱
外企场景- error
Failing to map letters correctly to their mirror equivalents.
- error
Forgetting to check the corresponding mirror stack before pushing the current character.
- error
Using nested loops instead of stacks, leading to O(n^2) performance.
进阶变体
外企场景- arrow_right_alt
Compute mirror scores with uppercase and lowercase letters combined.
- arrow_right_alt
Modify the problem to allow partial mirror pairs with a tolerance of one mismatch.
- arrow_right_alt
Calculate maximum mirror score after deleting at most k characters from s.