[Leetcode] 1528. Shuffle String
2023. 1. 12. 12:54ㆍPython/algorithm
Problem
이번 문제는 s 라는 문자열이 주어지고 indices에 s 문자열 각자리의 알맞는 인덱스가 들어가있고 정렬해서 return 해주는 문제이다.
나의 풀이
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
res = ''
zipped = sorted(zip(indices, s), key=lambda x: x[0])
for idx,char in zipped:
res += char
return res
zip으로 두개를 묶고 , 인덱스를 기준으로 정렬한 뒤에 res에 더해주고 return 해 주었어용
다른 사람의 풀이 두가지를 보자
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
re = [''] * len(indices)
for index, char in zip(indices, s):
re[index] = char
return "".join(re)
이 분은 정렬을 하지않고 인덱스를 이용해서 더해주고 풀었어용
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
mydict=dict(zip(indices,s))
return "".join([mydict[key] for key in sorted(mydict)])
설마 더 짧아 지겠나햇는데 더 짧아집니다 !
딕셔너리 활용을 하고 join을 활용했어용 굉장히 짧고 좋아용 ;
'Python > algorithm' 카테고리의 다른 글
[Leetcode] 2236. Root Equals Sum of Children (1) | 2023.01.11 |
---|---|
[Leetcode] 1365. How Many Numbers Are Smaller Than the Current Number (1) | 2023.01.05 |
[Leetcode] 1281. Subtract the Product and Sum of Digits of an Integer (2) | 2023.01.04 |
[Leetcode] 1431. Kids With the Greatest Number of Candies (1) | 2023.01.02 |
[Leetcode] 2413. Smallest Even Multiple (1) | 2022.12.31 |