LeetCode 题解工作台

字母移位

有一个由小写字母组成的字符串 s ,和一个长度相同的整数数组 shifts 。 我们将字母表中的下一个字母称为原字母的 移位 shift() (由于字母表是环绕的, 'z' 将会变成 'a' )。 例如, shift('a') = 'b' , shift('t') = 'u' , 以及 shift(…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·string

bolt

答案摘要

对于字符串 中的每个字符,我们需要计算其最终的偏移量,即 与 $\textit{shifts}[i + 1]$ 与 $\textit{shifts}[i + 2]$ ... 的和。我们可以使用后缀和的思想,从后往前遍历 ,计算每个字符的最终偏移量,然后对 取模,得到最终的字符。 时间复杂度 ,其中 为字符串 的长度。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个由小写字母组成的字符串 s,和一个长度相同的整数数组 shifts

我们将字母表中的下一个字母称为原字母的 移位 shift() (由于字母表是环绕的, 'z' 将会变成 'a')。

  • 例如,shift('a') = 'b'shift('t') = 'u', 以及 shift('z') = 'a'

对于每个 shifts[i] = x , 我们会将 s 中的前 i + 1 个字母移位 x 次。

返回 将所有这些移位都应用到 s 后最终得到的字符串

 

示例 1:

输入:s = "abc", shifts = [3,5,9]
输出:"rpl"
解释: 
我们以 "abc" 开始。
将 S 中的第 1 个字母移位 3 次后,我们得到 "dbc"。
再将 S 中的前 2 个字母移位 5 次后,我们得到 "igc"。
最后将 S 中的这 3 个字母移位 9 次后,我们得到答案 "rpl"。

示例 2:

输入: s = "aaa", shifts = [1,2,3]
输出: "gfd"

 

提示:

  • 1 <= s.length <= 105
  • s 由小写英文字母组成
  • shifts.length == s.length
  • 0 <= shifts[i] <= 109
​​​​​​
lightbulb

解题思路

方法一:后缀和

对于字符串 ss 中的每个字符,我们需要计算其最终的偏移量,即 shifts[i]\textit{shifts}[i]shifts[i+1]\textit{shifts}[i + 1]shifts[i+2]\textit{shifts}[i + 2] ... 的和。我们可以使用后缀和的思想,从后往前遍历 shifts\textit{shifts},计算每个字符的最终偏移量,然后对 2626 取模,得到最终的字符。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def shiftingLetters(self, s: str, shifts: List[int]) -> str:
        n, t = len(s), 0
        s = list(s)
        for i in range(n - 1, -1, -1):
            t += shifts[i]
            j = (ord(s[i]) - ord('a') + t) % 26
            s[i] = ascii_lowercase[j]
        return ''.join(s)
speed

复杂度分析

指标
时间O(N)
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of how to efficiently handle repeated shifts using a prefix sum.

  • question_mark

    Evaluate the candidate's ability to handle string transformations and modulo operations.

  • question_mark

    Check how well the candidate can apply optimizations to avoid unnecessary recomputations.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the shift operation by not properly wrapping around the alphabet.

  • error

    Failing to efficiently calculate shifts by not using a prefix sum or cumulative sum approach.

  • error

    Ignoring the modulo operation for large shift values that exceed 26, leading to incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Changing the alphabet to a different set of characters (e.g., uppercase letters or custom characters).

  • arrow_right_alt

    Introducing a variation where shifts are applied in reverse order (i.e., starting from the last element of the array).

  • arrow_right_alt

    Handling larger shift values more efficiently by implementing a custom modulo-based transformation.

help

常见问题

外企场景

字母移位题解:数组·string | LeetCode #848 中等