๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก - python

BAY 2023. 10. 30. 15:53
728x90

์ฝ”๋“œ

์‹œ๊ฐ„ ์ดˆ๊ณผ ์ฝ”๋“œ

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

์‹œ๊ฐ„๋ณต์žก๋„(big-O)์— ๋ฐ์ดํ„ฐ ํฌ๊ธฐ(n)์„ ๋„ฃ์–ด์„œ ๋‚˜์˜จ ๊ฐ’์ด 100,000,000(1์–ต)์ด ๋„˜์œผ๋ฉด ์‹œ๊ฐ„ ์ œํ•œ ์ดˆ๊ณผํ•  ๊ฐ€๋Šฅ์„ฑ ์žˆ์Œ !

for๋ฌธ์„ 2๋ฒˆ์“ฐ๋ฉด ์ตœ์•…์˜ ๊ฒฝ์šฐ O(N^2)

1 ≤ phone_book ≤ 1000000 ์ด๋ฏ€๋กœ, O(N^2)์€ ์•ˆ๋จ.

 

https://thals.tistory.com/214

 

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก - python

๋ฌธ์ œ ์ •๋ณด https://school.programmers.co.kr/learn/courses/30/lessons/42577 ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ

thals.tistory.com

๋†€๋ž๊ฒŒ๋„ ์ด๋•Œ์™€ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค ใ…‹ ใ…‹

์‹œ๊ฐ„๋ณต์žก๋„ ์ƒ๊ฐํ•˜๋ฉด์„œ ๋ฌธ์ œ ํ’€์œผ๋ผ๊ณ  ! ! ! ! ! 

 

์ •๋‹ต ์ฝ”๋“œ

def solution(phone_book):
    phone_book.sort()
    for i in range(len(phone_book)-1):
        if phone_book[i] == phone_book[i+1][:len(phone_book[i])]:
            return False
    return True
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
l = ['10', '1', '5']

print(sorted(l))
# ['1', '10', '5']

string์˜ sort ๋ฐฉ๋ฒ•์„ ๋ณด๋ฉด ์ˆซ์ž ์ž๋ฆฟ์ˆ˜

728x90