LeetCode 题解工作台

重新排列字符串

给你一个字符串 s 和一个 长度相同 的整数数组 indices 。 请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。 返回重新排列后的字符串。 示例 1: 输入: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 输出…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们创建一个与字符串长度相同的字符数组或字符串 ,然后遍历字符串 ,将每个字符 放置到 的 位置上。最后将字符数组或字符串 拼接成最终结果并返回。 时间复杂度 ,空间复杂度 ,其中 是字符串的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 == n
  • 1 <= n <= 100
  • s 仅包含小写英文字母
  • 0 <= indices[i] < n
  • indices 的所有的值都是 唯一
lightbulb

解题思路

方法一:模拟

我们创建一个与字符串长度相同的字符数组或字符串 ans\textit{ans},然后遍历字符串 s\textit{s},将每个字符 s[i]\textit{s}[i] 放置到 ans\textit{ans}indices[i]\textit{indices}[i] 位置上。最后将字符数组或字符串 ans\textit{ans} 拼接成最终结果并返回。

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

1
2
3
4
5
6
7
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)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

重新排列字符串题解:数组·string | LeetCode #1528 简单