基于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, yourreslist grows by 1 element. - After 8 iterations, your
reslist 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]:
- Initial
res:['', '', '', '', '', '', '', ''](length 8) - First loop (i=0):
insert(4, 'c')→resbecomes['', '', '', '', 'c', '', '', '', ''](length 9) - Second loop (i=1):
insert(5, 'o')→resbecomes['', '', '', '', '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)
- Initial
res:['', '', '', '', '', '', '', ''](length 8) - i=0:
res[4] = 'c'→res = ['', '', '', '', 'c', '', '', ''] - i=1:
res[5] = 'o'→res = ['', '', '', '', 'c', 'o', '', ''] - i=4:
res[0] = 'l'→res = ['l', '', '', '', 'c', 'o', '', '']
...
By the end of the loop, every position inresis filled with the correct character. Joining it gives you the desired"leetcode".
内容的提问来源于stack exchange,提问作者Rawan Ghanem
相关产品推荐
相关产品推荐

