-
99클럽(2기) - 코테스터디 21일차 TIL # Array # StringAlgorithm 2024. 6. 18. 23:21
LeetCode - 1528. Shuffle String
You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
1. 첫 번째 풀이
1) s를 구성하는 글자의 인덱스와 해당 글자를 담을 딕셔너리 strings 생성
defaultdict를 이용해 s를 구성하는 글자의 인덱스를 키로, 해당 글자를 값으로 갖는 딕셔너리 strings를 생성한다.
2) s를 순회하며 indices[idx]를 키, letter를 값으로 strings에 저장
letter는 s의 글자 하나하나를 의미하며, letter의 인덱스는 idx다. indices에서 현재 letter와 대응되는 idx를 키로, letter를 값으로 하는 키-값 쌍을 strings에 추가해준다.
3) strings를 정렬해 sorted_strings 생성
기존의 s를 순서대로 정렬해야 하므로 s의 요소(letter)의 인덱스(idx)와 해당 요소를 가지고 있는 strings를 정렬한다. sorted
4) sorted_string의 두 번째 요소만 join해서 합쳐진 문자열 반환
sorted_strings의 요소 sorted_string은 (키, 값)으로 이루어진 튜플이다. 값인 letter만 필요하므로 모든 sorted_string에 대해서 sorted_string의 두 번째 요소인 letter만 join으로 합친 문자열을 반환한다.
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: # s의 글자 하나하나와 매핑되는 인덱스로 구성된 딕셔너리 strings = defaultdict(str) # s를 순회하며 indices[idx]를 키, letter를 값으로 strings에 저장 for idx, letter in enumerate(s): strings[indices[idx]] = letter # strings의 키를 기준으로 정렬 sorted_strings = sorted(strings.items()) # sorted_string의 두번째 요소(값)만 리스트에 담은 후 join으로 합친 문자열 반환 return "".join([sorted_string[1] for sorted_string in sorted_strings])
2. ChatGPT의 풀이
1) 결과를 저장할 리스트 sorted_strings를 s와 같은 길이로 초기화
s의 길이 개수 만큼의 빈 문자열을 요소로 갖는 리스트 sorted_strings를 생성한다.
2) 각 문자를 올바른 위치에 재배치
zip함수를 이용해서 indicies와 s의 요소 letter의 인덱스 idx와 letter를 튜플로 묶은 이터러블 객체를 생성하고 sorted_strings에 idx로 접근해서 해당 인덱스에 letter를 저장한다. 인덱스를 지정하는 과정에서 자연스럽게 재배치 된다.
3) sorted_strings를 join해서 문자열로 변환하여 반환
join 함수를 이용해 공백 없이 sorted_strings의 요소들을 합친 문자열을 반환한다.
class Solution: def restoreString(s: str, indices: List[int]) -> str: # 정렬된 결과를 저장할 sorted_list를 s와 같은 길이로 초기화 sorted_strings = [''] * len(s) # 각 문자를 올바른 위치에 배치 for idx, letter in zip(indices, s): sorted_strings[idx] = letter # sorted_strings를 문자열로 변환하여 반환 return ''.join(sorted_strings)
3. 느낀점
defaultdict를 쓸 필요가 없었는데 저번에 풀었던 문제에서 defaultdict를 썼었던 것이 떠올라 그냥 사용했다. 특정 기능을 왜 써야하는지, 꼭 써야하는지, 장단점은 뭔지! 쓰기 전에 생각해보자. 항상 나의 생각을 제 3자의 시선으로 분석해보자.
'Algorithm' 카테고리의 다른 글
99클럽(2기) - 코테스터디 25일차 TIL # Stack (3) 2024.06.25 99클럽(2기) - 코테스터디 22일차 TIL # String (0) 2024.06.20 99클럽(2기) - 코테스터디 20일차 TIL # Array (0) 2024.06.18 99클럽(2기) - 코테스터디 19일차 TIL # 완전 탐색 (0) 2024.06.17 99클럽(2기) - 코테스터디 18일차 TIL # Array (0) 2024.06.15