View

문제 설명

문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.


제한사항
  • 1 ≤ my_string ≤ 110
  • my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.
  • 대문자와 소문자를 구분합니다.
  • 공백(" ")도 하나의 문자로 구분합니다.
  • 중복된 문자 중 가장 앞에 있는 문자를 남깁니다.

입출력 예my_stringresult
"people" "peol"
"We are the world" "We arthwold"

입출력 예 설명

입출력 예 #1

  • "people"에서 중복된 문자 "p"와 "e"을 제거한 "peol"을 return합니다.

입출력 예 #2

  • "We are the world"에서 중복된 문자 "e", " ", "r" 들을 제거한 "We arthwold"을 return합니다.

나의 풀이

dictionary의 정렬은 dict.items()를 통해 키와 값을 튜플로 만든 후
기준으로 정렬할, key를 람다함수로 정의해주어, 정렬시켜준다.

def solution(my_string):
    s = {i:list(my_string).index(i) for i in list(set(my_string))}
    return ''.join([j[0] for j in sorted(s.items(), key=lambda x:x[1])])

다른 풀이 1

def solution(my_string):
    return ''.join(dict.fromkeys(my_string))

 

dict.fromkeys(keys, values)는 본래, dictionay를 생성할 때, 용이하게 하기 위해 사용하는 메서드이다.

dict.fromkeys("people", [10, 15])

>> {'p': [10, 15], 'e': [10, 15], 'o': [10, 15], 'l': [10, 15]}

dict.fromkeys("people") # 중복되는 키값은 사라진다.

>> {'p': None, 'e': None, 'o': None, 'l': None}


다른 풀이 2

answer에 있는 원소와 중복되는 값이 없으면, answer에 담는다.

def solution(my_string):
    answer = ''
    for i in my_string:
        if i not in answer:
            answer+=i
    return answer

 

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

programmers) A로 B 만들기  (0) 2022.11.08
programmers) 2차원으로 만들기  (0) 2022.11.08
programmers) 합성수 찾기  (0) 2022.11.08
programmers) 모스부호 (1)  (0) 2022.11.08
programmers) 369게임  (0) 2022.11.08
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31