天天看點

LeetCode 5472. 重新排列字元串

給你一個字元串 

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"
**解釋:**重新排列後,每個字元都還留在原來的位置上。

**示例 3:**

**輸入:**s = "aiohn", `indices` = [3,1,4,2,0]
**輸出:**"nihao"

**示例 4:**

**輸入:**s = "aaiougrt", `indices` = [4,0,2,6,7,3,1,5]
**輸出:**"arigatou"

**示例 5:**

**輸入:**s = "art", `indices` = [1,0,2]
**輸出:**"rat"           

解題思路

class Solution:
    def restoreString(self, s: str, indices: [int]) -> str:
        tempList = [""]*len(indices)
        strList = list(s)
        for idx,val in enumerate(indices):
            tempStr = strList[idx]
            tempList[val] = tempStr
        # print(tempList)
        return "".join(tempList)           

繼續閱讀