LeetCode 题解工作台
字符串的分数
给你一个字符串 s 。一个字符串的 分数 定义为相邻字符 ASCII 码差值绝对值的和。 请你返回 s 的 分数 。 示例 1: 输入: s = "hello" 输出: 13 解释: s 中字符的 ASCII 码分别为: 'h' = 104 , 'e' = 101 , 'l' = 108 , 'o'…
1
题型
8
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们直接遍历字符串 ,计算相邻字符的 ASCII 码差值的绝对值之和即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 s 。一个字符串的 分数 定义为相邻字符 ASCII 码差值绝对值的和。
请你返回 s 的 分数 。
示例 1:
输入:s = "hello"
输出:13
解释:
s 中字符的 ASCII 码分别为:'h' = 104 ,'e' = 101 ,'l' = 108 ,'o' = 111 。所以 s 的分数为 |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13 。
示例 2:
输入:s = "zaz"
输出:50
解释:
s 中字符的 ASCII 码分别为:'z' = 122 ,'a' = 97 。所以 s 的分数为 |122 - 97| + |97 - 122| = 25 + 25 = 50 。
提示:
2 <= s.length <= 100s只包含小写英文字母。
解题思路
方法一:模拟
我们直接遍历字符串 ,计算相邻字符的 ASCII 码差值的绝对值之和即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(a - b) for a, b in pairwise(map(ord, s)))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each character is visited once to compute its difference with the next. Space complexity is O(1) since only a running total and the previous character need storage. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if candidates correctly use ASCII values for adjacent characters.
- question_mark
Watch for unnecessary data structures that increase space usage.
- question_mark
Listen for clear explanation of the string-driven iterative pattern.
常见陷阱
外企场景- error
Forgetting to take the absolute value of differences.
- error
Attempting to store all differences instead of a running sum.
- error
Failing on repeated characters where difference is zero.
进阶变体
外企场景- arrow_right_alt
Compute the score using the difference between Unicode code points for extended character sets.
- arrow_right_alt
Return a cumulative array of scores at each position instead of a total sum.
- arrow_right_alt
Apply the same scoring method to a list of strings and return their maximum score.