LeetCode 题解工作台

字符串转化后的各位数字之和

给你一个由小写字母组成的字符串 s ,以及一个整数 k 。你的任务是通过一种特殊处理将字符串转为整数,然后通过重复对它的数位求和 k 次来进行转换。更具体地说,执行以下步骤: 用字母在字母表中的位置 替换 该字母,将 s 转化 为一个整数(也就是, 'a' 用 1 替换, 'b' 用 2 替换,..…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·模拟

bolt

答案摘要

根据题目描述进行模拟即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由小写字母组成的字符串 s ,以及一个整数 k 。你的任务是通过一种特殊处理将字符串转为整数,然后通过重复对它的数位求和 k 次来进行转换。更具体地说,执行以下步骤:

  1. 用字母在字母表中的位置 替换 该字母,将 s 转化 为一个整数(也就是,'a'1 替换,'b'2 替换,... 'z'26 替换)。
  2. 接着,将整数 转换 为其 各位数字之和
  3. 共重复 转换 操作(第 2 步) k

例如,如果 s = "zbax"k = 2 ,那么执行下述步骤后得到的结果是整数 8

  • 转化:"zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
  • 转换 #1262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
  • 转换 #217 ➝ 1 + 7 ➝ 8

返回执行上述 操作 后得到的 结果整数

 

示例 1:

输入:s = "iiii", k = 1
输出:36
解释:
操作如下:
  • 转化:"iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
  • 转换 #1:9999 ➝ 9 + 9 + 9 + 9 ➝ 36
因此,结果整数为 36 。
 

示例 2:

输入:s = "leetcode", k = 2
输出:6
解释:
操作如下:
  • 转化:"leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
  • 转换 #1:12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
  • 转换 #2:33 ➝ 3 + 3 ➝ 6

因此,结果整数为 6 。

 

示例 3:

输入:s = "zbax", k = 2

输出:8

 

提示:

  • 1 <= s.length <= 100
  • 1 <= k <= 10
  • s 由小写英文字母组成
lightbulb

解题思路

方法一:模拟

根据题目描述进行模拟即可。

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

1
2
3
4
5
6
7
8
class Solution:
    def getLucky(self, s: str, k: int) -> int:
        s = ''.join(str(ord(c) - ord('a') + 1) for c in s)
        for _ in range(k):
            t = sum(int(c) for c in s)
            s = str(t)
        return int(s)
speed

复杂度分析

指标
时间complexity is O(n) for the initial string conversion and digit summing, where n is the length of s. Space complexity is O(1) since we reuse variables and the digit sum strings are short and bounded.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for correct mapping of letters to numbers without skipping steps.

  • question_mark

    Checking if the candidate handles repeated digit summation efficiently.

  • question_mark

    Verifying understanding of string plus simulation pattern to avoid unnecessary integer parsing.

warning

常见陷阱

外企场景
  • error

    Trying to convert the entire concatenated string to integer at once, risking overflow.

  • error

    Performing k transformations recursively without realizing iterative summing suffices.

  • error

    Ignoring that after the first transform, the number is small enough for simple summing.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change k to a large number and optimize by observing digital root properties.

  • arrow_right_alt

    Use uppercase letters and handle case-insensitive conversion to positions.

  • arrow_right_alt

    Instead of sum, perform product of digits repeatedly k times to modify the simulation pattern.

help

常见问题

外企场景

字符串转化后的各位数字之和题解:string·结合·模拟 | LeetCode #1945 简单