Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.

[2023-08-21] sumin #136 #148

Merged
merged 1 commit into from
Aug 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions Programmers - 문제풀이/전화번호 목록/sumin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
풀이시간: 10분

<input>
- phone_book의 길이: 1 이상 1,000,000 이하
- 각 전화번호의 길이: 1 이상 20 이하
- 같은 전화번호가 중복해서 들어있지 않다.

<solution>
1) 정렬 후 현재 확인하고 있는 번호가 다음 번호의 접두어인지 확인하는 방법
2) 해시를 이용해 특정 전화번호의 접두어가 다른 번호인지 확인하는 방법

<시간 복잡도>
1) O(nlogn)
2) O(nm): n은 전화번호의 총 개수, m은 최대

<기타>
이 외에 트라이로도 풀이 가능
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

트라이는 또 뭡니까?! ㅋㅋㅋㅋㅋㅋ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저번에 말했던 검색 엔진에 많이 사용하는 알고리즘이용 Trie!

"""

from typing import List

# 정렬로 풀기
def solution(phone_book: List) -> bool:
# 전화번호를 사전순으로 정렬
phone_book.sort()

for i in range(len(phone_book) - 1):
# 다음 번호 비교 -> 접두어인지 확인
if phone_book[i+1].startswith(phone_book[i]): # 접두어인 경우
return False
return True


# 해시로 풀기
def solution(phone_book: List) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해시로 푼 풀이가 인상깊었습니다! 이번 문제 효율은 역시 정렬의 풀이가 빠르겠지만 해시 테이블로도 풀이가 가능하다는 것에 의미가 있는 것 같습니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 해시 풀이 잘 보고갑니다!! 이번 문제 외에도 보편적으로 특정 키를 찾을 때 유용하게 사용할 수 있을 거 같아서 좋네요!!

phone_hash = {} # 전화번호 접두사를 저장할 해시

# 각 전화번호의 접두사를 해시에 저장
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

왜 문제의 주제가 해시인지 몰랐었는데 풀이를 보고 이해가 되었습니다. 해시를 활용하지 않는다면 이 반복문이 필요가 없이 phone_book을 참조하면 되는 것인데, 해시 참조의 효율성 때문에 해시를 만들어서 시간 내에 문제를 해결할 수 있군요! 도움이 많이 되었습니다.

for number in phone_book:
phone_hash[number] = True

for number in phone_book:
for i in range(1, len(number)):
prefix = number[:i]
if prefix in phone_hash: # 접두어인 경우
return False
return True


# 테스트 케이스
test_case1 = ["119", "97674223", "1195524421"] # 출력: False
test_case2 = ["123","456","789"] # 출력: True
test_case3 = ["12","123","1235","567","88"] # 출력: False
test_case4 = ["456", "467"] # 출력: True
test_case5 = ["1195524421", "97674223", "119"] # 출력: False

print(solution(phone_book=test_case5))