LeetCode 题解工作台
字符串的反转度
给你一个字符串 s ,计算其 反转度 。 反转度 的计算方法如下: 对于每个字符,将其在 反转 字母表中的位置( 'a' = 26, 'b' = 25, ..., 'z' = 1)与其在字符串中的位置(下标从 1 开始)相乘。 将这些乘积加起来,得到字符串中所有字符的和。 返回 反转度 。 示例 1…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · string·结合·模拟
答案摘要
我们可以模拟字符串中每个字符的反转度。对于每个字符,我们计算它在反转字母表中的位置,然后乘以它在字符串中的位置,最后将所有结果相加即可。 时间复杂度 ,其中 是字符串的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
给你一个字符串 s,计算其 反转度。
反转度的计算方法如下:
- 对于每个字符,将其在 反转 字母表中的位置(
'a'= 26,'b'= 25, ...,'z'= 1)与其在字符串中的位置(下标从1 开始)相乘。 - 将这些乘积加起来,得到字符串中所有字符的和。
返回 反转度。
示例 1:
输入: s = "abc"
输出: 148
解释:
| 字母 | 反转字母表中的位置 | 字符串中的位置 | 乘积 |
|---|---|---|---|
'a' |
26 | 1 | 26 |
'b' |
25 | 2 | 50 |
'c' |
24 | 3 | 72 |
反转度是 26 + 50 + 72 = 148 。
示例 2:
输入: s = "zaza"
输出: 160
解释:
| 字母 | 反转字母表中的位置 | 字符串中的位置 | 乘积 |
|---|---|---|---|
'z' |
1 | 1 | 1 |
'a' |
26 | 2 | 52 |
'z' |
1 | 3 | 3 |
'a' |
26 | 4 | 104 |
反转度是 1 + 52 + 3 + 104 = 160 。
提示:
1 <= s.length <= 1000s仅包含小写字母。
解题思路
方法一:模拟
我们可以模拟字符串中每个字符的反转度。对于每个字符,我们计算它在反转字母表中的位置,然后乘以它在字符串中的位置,最后将所有结果相加即可。
时间复杂度 ,其中 是字符串的长度。空间复杂度 。
class Solution:
def reverseDegree(self, s: str) -> int:
ans = 0
for i, c in enumerate(s, 1):
x = 26 - (ord(c) - ord("a"))
ans += i * x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ensure the candidate correctly simulates the reverse position of each character.
- question_mark
Watch for an efficient solution that avoids unnecessary recalculations.
- question_mark
Look for proper handling of edge cases like strings of minimal and maximal length.
常见陷阱
外企场景- error
Misunderstanding the reverse alphabet positioning, leading to incorrect calculations.
- error
Recalculating character positions multiple times rather than storing values for efficiency.
- error
Forgetting to properly handle the string length limits and failing to optimize for larger inputs.
进阶变体
外企场景- arrow_right_alt
Consider extending the problem to handle mixed-case strings and their reverse degree.
- arrow_right_alt
Change the problem to calculate the forward degree and compare the solutions.
- arrow_right_alt
Challenge the candidate to optimize the solution further with a different approach, like using precomputed values.