208. Implement Trie (Prefix Tree)

2021. 5. 18. 10:23·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
'Algorithm' 카테고리의 다른 글
  • 108. Convert Sorted Array to Binary Search Tree
  • 300. Longest Increasing Subsequence
  • 240. Search a 2D Matrix II
  • 279. Perfect Squares
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (349)
      • Programming (54)
      • Algorithm (161)
      • Review (102)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    db
    database
    line
    면접
    2023
    인프콘
    jpa
    나는 리뷰어다
    BOJ
    sql
    라인
    leetcode
    2021
    ChatGPT
    2022
    공채
    mysql
    개발자
    한빛미디어
    코딩
    AI
    백준
    sql튜닝
    PYTHON
    프로그래머스
    컨퍼런스
    java
    코딩테스트
    회고
    나는리뷰어다
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
208. Implement Trie (Prefix Tree)
상단으로

티스토리툴바