Zero to Hero
article thumbnail
Published 2021. 5. 18. 10:23
208. Implement Trie (Prefix Tree) Algorithm
 

Implement Trie (Prefix Tree) - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. Trie 자료구조 구현

class Trie:
    def __init__(self):
        self.head = Node()

    def insert(self, word: str) -> None:
        cur = self.head
        for char in word:
            if char not in cur.child:
                new_node = Node(char)
                cur.child[char] = new_node
            cur = cur.child[char]
        cur.child["*"] = "!"

    def search(self, word: str) -> bool:
        cur = self.head
        for char in word:
            if char not in cur.child:
                return False
            cur = cur.child[char]
        if "*" in cur.child:
            return True

    def startsWith(self, prefix: str) -> bool:
        cur = self.head
        for char in prefix:
            if char not in cur.child:
                return False
            cur = cur.child[char]
        return True


class Node:
    def __init__(self, val="0"):
        self.val = val
        self.child = {}

    def __str__(self):
        return f"val: {self.val}, child:{self.child}"

스스로도 한 번에 통과해서 놀랐다.

Trie 정도는 어느샌가 그냥 구현할 수 있게 되어서 나름대로 만족한다.

'Algorithm' 카테고리의 다른 글

108. Convert Sorted Array to Binary Search Tree  (0) 2021.05.23
300. Longest Increasing Subsequence  (0) 2021.05.19
240. Search a 2D Matrix II  (0) 2021.05.18
279. Perfect Squares  (0) 2021.05.17
236. Lowest Common Ancestor of a Binary Tree  (0) 2021.05.17
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!