say repository

[프로그래머스] 전화번호 목록 python 본문

알고리즘 문제 풀이/프로그래머스

[프로그래머스] 전화번호 목록 python

부끄러엇피치 2022. 3. 25. 00:44
728x90

출처 : 프로그래머스

https://programmers.co.kr/learn/courses/30/lessons/42577

 

코딩테스트 연습 - 전화번호 목록

전화번호부에 적힌 전화번호 중, 한 번호가 다른 번호의 접두어인 경우가 있는지 확인하려 합니다. 전화번호가 다음과 같을 경우, 구조대 전화번호는 영석이의 전화번호의 접두사입니다. 구조

programmers.co.kr

def solution(phone_book):
    answer = True
    # 전화번호부 해시 생성
    hashmap = {}
    for phone_num in phone_book:
        hashmap[phone_num] = 1

    # 접두사 찾기
    for phone_num in phone_book:
        tmp = ''
        for num in phone_num:
            tmp += num
            # 하나씩 입력한 전화번호의 번호가 해쉬맵에 있고 자기 자신 번호가 아닐 때
            if tmp in hashmap and tmp != phone_num:
                answer = False
    return answer

풀이 1

해시 문제라 해시로 풀이했다.

전화번호를 해시 맵에 입력해주고,

한 사람의 전화번호의 번호를 tmp에 저장하고 hashmap에 있는 전화번호와 비교하며 자기 자신인 경우를 제외한다.

def solution(phone_book):
    answer = True
    pbook = sorted(phone_book)

    for a,b in zip(pbook, pbook[1:]):
        if b.startswith(a):
            return False
    return answer

풀이 2

전화번호가 문자열이니 정렬하고 두 번째 전화번호부터 비교한다.

startswith()를 사용했다.