You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Indices数组的字符串重排问题:我的Python解法错误原因咨询

Why Your restoreString Code Fails for the Given Example

Hey there! Let's break down exactly why your implementation isn't producing the correct result, and fix it up along the way.

The Core Problem: Using insert() Instead of Direct Assignment

You started off on the right foot by initializing res = [''] * len(s)—this creates a list with the exact length we need (8 in the example). But the mistake happens with the res.insert(indices[i], s[i]) line:

  • The insert() method adds a new element at the specified index and shifts all existing elements after it to the right. This means every time you call it, your res list grows by 1 element.
  • After 8 iterations, your res list will be 16 elements long (the original 8 empty strings plus 8 inserted characters). When you join this list, you're including all those extra empty strings and misplaced characters, which is why you don't get "leetcode".

Let's Walk Through the First Few Steps to See the Mess

Take the example input s = "codeleet", indices = [4,5,6,7,0,2,1,3]:

  1. Initial res: ['', '', '', '', '', '', '', ''] (length 8)
  2. First loop (i=0): insert(4, 'c') → res becomes ['', '', '', '', 'c', '', '', '', ''] (length 9)
  3. Second loop (i=1): insert(5, 'o') → res becomes ['', '', '', '', 'c', 'o', '', '', '', ''] (length 10)
    ...
    By the end, you've got a bloated list with extra empty strings and characters in the wrong spots—definitely not what we want.

The Simple Fix: Assign Directly to the Index

Instead of inserting, we just need to overwrite the empty string at the target index with our character. Since we already initialized res to the correct length, we can directly set values at specific positions:

class Solution:
    def restoreString(self, s, indices):
        res = [''] * len(s)
        for i in range(len(s)):
            res[indices[i]] = s[i]  # Replace insert with direct assignment
        return "".join(res)

How This Works (Step-by-Step for the Example)

  1. Initial res: ['', '', '', '', '', '', '', ''] (length 8)
  2. i=0: res[4] = 'c' → res = ['', '', '', '', 'c', '', '', '']
  3. i=1: res[5] = 'o' → res = ['', '', '', '', 'c', 'o', '', '']
  4. i=4: res[0] = 'l' → res = ['l', '', '', '', 'c', 'o', '', '']
    ...
    By the end of the loop, every position in res is filled with the correct character. Joining it gives you the desired "leetcode".

内容的提问来源于stack exchange,提问作者Rawan Ghanem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 12:23:11