LeetCode 题解工作台

字符串的分数

给你一个字符串 s 。一个字符串的 分数 定义为相邻字符 ASCII 码差值绝对值的和。 请你返回 s 的 分数 。 示例 1: 输入: s = "hello" 输出: 13 解释: s 中字符的 ASCII 码分别为: 'h' = 104 , 'e' = 101 , 'l' = 108 , 'o'…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们直接遍历字符串 ,计算相邻字符的 ASCII 码差值的绝对值之和即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 100
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一:模拟

我们直接遍历字符串 ss,计算相邻字符的 ASCII 码差值的绝对值之和即可。

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def scoreOfString(self, s: str) -> int:
        return sum(abs(a - b) for a, b in pairwise(map(ord, s)))
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

字符串的分数题解:String-driven solution … | LeetCode #3110 简单