LeetCode 题解工作台
重新排列字符串
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。 请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。 返回重新排列后的字符串。 示例 1: 输入: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 输出…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们创建一个与字符串长度相同的字符数组或字符串 ,然后遍历字符串 ,将每个字符 放置到 的 位置上。最后将字符数组或字符串 拼接成最终结果并返回。 时间复杂度 ,空间复杂度 ,其中 是字符串的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
示例 1:

输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
示例 2:
输入:s = "abc", indices = [0,1,2]
输出:"abc"
解释:重新排列后,每个字符都还留在原来的位置上。
提示:
s.length == indices.length == n1 <= n <= 100s仅包含小写英文字母0 <= indices[i] < nindices的所有的值都是 唯一 的
解题思路
方法一:模拟
我们创建一个与字符串长度相同的字符数组或字符串 ,然后遍历字符串 ,将每个字符 放置到 的 位置上。最后将字符数组或字符串 拼接成最终结果并返回。
时间复杂度 ,空间复杂度 ,其中 是字符串的长度。
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
ans = [None] * len(s)
for c, j in zip(s, indices):
ans[j] = c
return "".join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each character is moved exactly once. Space complexity is O(n) if using an auxiliary array; in-place swaps can reduce space to O(1) but add bookkeeping overhead. The primary cost comes from handling the array mapping efficiently without collisions or overwrites. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you recognize that direct mapping from indices is the simplest approach?
- question_mark
Have you considered space-efficient in-place rearrangement versus auxiliary array?
- question_mark
Can you handle edge cases like already sorted or reversed indices arrays?
常见陷阱
外企场景- error
Overwriting characters without tracking positions leading to incorrect results.
- error
Confusing indices positions with string positions during iteration.
- error
Ignoring constraints on unique indices causing unexpected duplication or gaps.
进阶变体
外企场景- arrow_right_alt
Shuffle string with repeated characters and duplicate index handling.
- arrow_right_alt
Shuffle string with partial indices and leaving some characters in place.
- arrow_right_alt
Shuffle string in-place without using extra array to minimize space complexity.