Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
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
Tags
more
Archives
Today
Total
관리 메뉴

하루에 하나씩 공부하기

전화번호 목록-LV2 본문

파이썬

전화번호 목록-LV2

dltaexox 2025. 2. 27. 22:05

- 문

전화번호부에 적힌 전화번호를 담은 배열 phone_book 이 solution 함수의 매개변수로 주어질 때, 어떤 번호가 다른 번호의 접두어인 경우가 있으면 false를 그렇지 않으면 true를 return 하도록 solution 함수를 작성해주세요.

 

코딩테스트 연습 - 전화번호 목록 | 프로그래머스 스쿨

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

- 키포인트

접두사 : .startswith()

접미사 : .endswith()

hash_table 생성 및 key 값 부여

 

- 코드

def solution(phone_book):
    phone_book.sort()
    for i in range(len(phone_book)-1):
        if phone_book[i+1].startswith(phone_book[i]):
            return False
    return True

 

리스트 정렬 후, startswith로 접두사로 시작하는 원소 있는지 확인

있으면 False 없으면 True 반환

def solution(phone_book):
    hash_map={}
    for number in phone_book:
        hash_map[number]=1
    for number in hash_map:
        for i in range(1, len(number)):
          prefix=number[:i]
          if prefix in hash_map:
            return False
    return True

해시 사용 -> hash_map 생성 후 의미없는 value인 1 값 부여

이후 반복문 통해 인덱싱 된 값이 hash_map에 있으면 return 값 변경

'파이썬' 카테고리의 다른 글

K번째수-LV1  (0) 2025.03.09
베스트앨범-LV3  (1) 2025.03.09
의상-LV2  (0) 2025.02.28
완주하지 못한 선수-LV1  (0) 2025.02.25
폰켓몬-LV1  (0) 2025.02.25