코딩테스트/코딩 테스트 입문
중복된 문자 제거
kimyongjun0129
2025. 3. 10. 22:34
# 내 풀이
def solution(my_string):
answer = ''
for word in my_string:
if word not in answer:
answer += word
return answer
- if word not in answer : answer 안에 word가 없을 경우, 조건이 True이다.
# GPT 풀이
def solution(my_string):
return "".join(dict.fromkeys(my_string))
- dict.fromkeys(my_string) : 입력 문자열의 문자들을 키로 갖는 dict 생성 (순서 유지 & 중복 제거)
- " ".join(...) : 딕셔너리의 키들을 문자열로 결합하여 반환
# dict.fromkeys(iterable, value=None, /)
- iterable이 제공하는 값들을 키로 사용하고 모든 값을 value로 설정한 새 딕셔너리를 돌려준다.
- fromkeys() : 새로운 딕셔너리를 돌려주는 클래스 메서드이다. value의 기본값은 None이다.
def solution(my_string):
print(dict.fromkeys(my_string)) // 결과 : {'p': None, 'e': None, 'o': None, 'l': None}
print("".join(dict.fromkeys(my_string))) // 결과 : peol