파이썬 알고리즘 인터뷰 56. 트라이 구현

2024. 3. 19. 19:38코딩 테스트/파이썬 알고리즘 인터뷰

https://leetcode.com/problems/implement-trie-prefix-tree/description/

 

전체 코드

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.word = True

    def search(self, word: str) -> bool:
        node = self.root
        for ch in word:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return node.word

    def startsWith(self, prefix: str) -> bool:
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return True

풀이

insert

insert 함수의 경우 "apple"을 입력시 다음과 같이 초기화 된다. 

def insert(self, word: str) -> None:
    node = self.root
    for ch in word:
        if ch not in node.children:
            node[ch] = TrieNode()
        node = node.children[ch]
    node.word = True

 

word를 순회하며 문자 ch가 node.children 딕셔너리에 없을 경우 단어를 추가하고 TrieNode로 초기화한다. 이후 node 포인터를 해당 TrieNode로 이동한다. 

word 루프 순회가 끝났다면 마지막 문자는 단어가 되므로 word=True로 설정한다. 

 

search, startWith

def search(self, word: str) -> bool:
    node = self.root
    for ch in word:
        if ch not in node.children:
            return False
        node = node.children[ch]
    return node.word

def startsWith(self, prefix: str) -> bool:
    node = self.root
    for ch in prefix:
        if ch not in node.children:
            return False
        node = node.children[ch]
    return True

search, startWith은 동작 방식이 거의 유사하다. 전달 받은 단어를 순회하며 깊이 우선으로 탐색을 진행하며 문자가 일치하지 않으면 False를 반환한다.

차이점은 search는 word=True로 끝나지 않으면 실패하고 startWith은 성공 처리를 한다.

"app"을 검색했을 때 Trie에서 단어로 처리되어 있지 않으면 search는 return False, startWith은 return True를 반환한다.