LeetCode 题解工作台
找出加密后的字符串
给你一个字符串 s 和一个整数 k 。请你使用以下算法加密字符串: 对于字符串 s 中的每个字符 c ,用字符串中 c 后面的第 k 个字符替换 c (以循环方式)。 返回加密后的字符串。 示例 1: 输入: s = "dart", k = 3 输出: "tdar" 解释: 对于 i = 0 , '…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以使用模拟的方法,对字符串的第 个字符,我们将其替换为字符串的第 $(i + k) \bmod n$ 个字符。 时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 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 <= 1001 <= k <= 104s仅由小写英文字母组成。
解题思路
方法一:模拟
我们可以使用模拟的方法,对字符串的第 个字符,我们将其替换为字符串的第 个字符。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.