특정 전화번호가 다른 전화번호의 접두어(앞에서부터 시작하는 글자)인지 확인하는 간단한 문제이다. 파이썬에는 startswith
라는 내장 함수가 있는데, 기능은 다음과 같다.
str1 = "MyNameIsMJ"
str2 = "MyNa"
str3 = "MNI"
print(str1.startswith(str2))
print(str1.startswith(str3))
>>True
>>False
따라서, startswith
를 사용하면 짧고 간결한 코드로 이 문제를 끝낼 수 있다. 그리고, 필요한 비교 횟수는 nC2와 같다. 한 번 비교한 것은 두 번 비교할 필요가 없기 때문. 그래서 전화번호를 정렬해준 후 phone_book[i]
과 phone_book[i:]
의 원소를 1:1로 비교해주면 된다.
def solution(phone_book):
#lambda식을 이용한 정렬 - 전화번호의 index 순서대로,
#같을 경우 길이가 짧은 것 우선
phone_book = sorted(phone_book, key = lambda x : (x, len(x)))
for find, target in zip(phone_book, phone_book[1:]):
if target.startswith(find):
return False
return True