728x90

 

오늘의 문제

https://leetcode.com/problems/shuffle-string/description/

 

class Solution:
    def restoreString(self, s: str, indices: List[int]) -> str:
        result = ['']*len(s)
        for i, index in enumerate(indices):
            result[index] = s[i]
        return ''.join(result)

 

일단 이번 문제에서는 파이썬에 대한 새로운 걸 많이 알아간거같다.

 

처음에 result = [] 로 array 초기화 했었는데

* 참고 ::  [] 리스트 {} 딕셔너리

자꾸 IndexError: list index out of range가 나서 왜이러나 싶었음

 

근데 result = [''] * len(s) 하니까 s 의 길이만큼 빈 문자열 리스트를 생성해줘서 index어쩌구는 안떴음

# ['', '', '', '', '', '', '', '']

 

아무튼 만약 길이가 8이라면

저런식으로 생성될것임.

 

``````````````````````````````````````

for i, index in enumerate(indices):
    result[index] = s[i]

``````````````````````````````````````

에서 enumerate 는 indices 리스트의 각 요소와 그 요소의 인덱스를 제공함

for i, index in enumerate(indices): 루프는 indices 리스트를 순회하면서 s 문자열의 각 문자를 result 리스트의 올바른 위치에 배치하고

최종적으로 result 리스트를 문자열로 변환하여 반환함

 

 

 

 

 

 

 

 

 

 

 

728x90

+ Recent posts