[프로그래머스] 1단계_숫자 문자열과 영단어 (python)

juyeon·2022년 6월 14일
0

코딩테스트(python)

목록 보기
4/22

프로그래머스

1단계_숫자 문자열과 영단어

나의 풀이

: 딕셔너리로 어찌어찌 하기는 했지만, 도저히 안나와서 흑흑

다른 사람 풀이(프로그래머스)

num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}
#key와 value 모두 str로 한게 포인트?

def solution(s):
    answer = s
    for key, value in num_dic.items():
        answer = answer.replace(key, value)
    return int(answer)
    #다시 int로

: 이건 O(N)처럼 보이지만 replace가 그 자체로 O(N) 이상이고 심지어는 O(N^2)까지도 가능한 메소드라 최악의 경우 O(N^3)까지 나옵니다. 풀이는 짧지만 시간 복잡도는 많이 커집니다.

def solution(s):
    words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

    for i in range(len(words)):
    #key로 숫자를 쓰는 대신, range로 숫자를...! 대단..
        s = s.replace(words[i], str(i))

    return int(s)
    #다시 int로 변환

: 둘다 깔끔하다.

profile
내 인생의 주연

0개의 댓글