LeetCode 题解工作台

找出加密后的字符串

给你一个字符串 s 和一个整数 k 。请你使用以下算法加密字符串: 对于字符串 s 中的每个字符 c ,用字符串中 c 后面的第 k 个字符替换 c (以循环方式)。 返回加密后的字符串。 示例 1: 输入: s = "dart", k = 3 输出: "tdar" 解释: 对于 i = 0 , '…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以使用模拟的方法,对字符串的第 个字符,我们将其替换为字符串的第 $(i + k) \bmod n$ 个字符。 时间复杂度 ,空间复杂度 。其中 是字符串 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 和一个整数 k。请你使用以下算法加密字符串:

  • 对于字符串 s 中的每个字符 c,用字符串中 c 后面的第 k 个字符替换 c(以循环方式)。

返回加密后的字符串。

 

示例 1:

输入: s = "dart", k = 3

输出: "tdar"

解释:

  • 对于 i = 0'd' 后面的第 3 个字符是 't'
  • 对于 i = 1'a' 后面的第 3 个字符是 'd'
  • 对于 i = 2'r' 后面的第 3 个字符是 'a'
  • 对于 i = 3't' 后面的第 3 个字符是 'r'

示例 2:

输入: s = "aaa", k = 1

输出: "aaa"

解释:

由于所有字符都相同,加密后的字符串也将相同。

 

提示:

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

解题思路

方法一:模拟

我们可以使用模拟的方法,对字符串的第 ii 个字符,我们将其替换为字符串的第 (i+k)modn(i + k) \bmod n 个字符。

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

1
2
3
4
5
6
7
8
class Solution:
    def getEncryptedString(self, s: str, k: int) -> str:
        cs = list(s)
        n = len(s)
        for i in range(n):
            cs[i] = s[(i + k) % n]
        return "".join(cs)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate understands string manipulation techniques.

  • question_mark

    The candidate efficiently uses modulo arithmetic to handle large values of k.

  • question_mark

    The candidate demonstrates awareness of time and space complexities in string-driven solutions.

warning

常见陷阱

外企场景
  • error

    Not using modulo to handle cases where k is greater than the string length, leading to incorrect results.

  • error

    Failing to handle edge cases such as when all characters are the same or when the string length is 1.

  • error

    Overcomplicating the solution by not optimizing for large values of k.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Shift characters based on different patterns or by using different encryption techniques.

  • arrow_right_alt

    Encrypt the string using a different shift amount for each character.

  • arrow_right_alt

    Handle cases where the string contains uppercase letters or non-alphabetic characters.

help

常见问题

外企场景

找出加密后的字符串题解:String-driven solution … | LeetCode #3210 简单