Skip to content

Commit

Permalink
implement trie solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jungsiroo committed Jan 6, 2025
1 parent fd2cd7a commit 3e2c6d9
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions implement-trie-prefix-tree/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Recursive vs Iterative
์žฌ๊ท€ ๋ฐฉ์‹์˜ ๊ฒฝ์šฐ, ๋งŒ์•ฝ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๊ต‰์žฅํžˆ ๊ธธ๋‹ค๋ฉด ๊ทธ๋งŒํผ์˜ ์ฝœ์ด ์ผ์–ด๋‚˜๊ณ  ์ด๋Š” ์„ฑ๋Šฅ์ ์œผ๋กœ ๋Š๋ ค์งˆ ์ˆ˜ ์žˆ์Œ.
๋‘ ๊ฐ€์ง€ ๋ชจ๋‘ ์‹œ๊ฐ„ ๋ณต์žก๋„ ๋ฉด์—์„œ๋Š” O(m) ์ž„ (m = len(string))
Node ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋‘์–ด ์ฒ˜๋ฆฌํ•˜๋ฉด ๊ฐ€๋…์„ฑ ๋†’๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.
"""

class Node:
def __init__(self, key=None):
self.key = key
self.children = {}
self.is_end = False

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

def insert(self, word: str) -> None:
curr = self.head

for ch in word:
if ch not in curr.children:
curr.children[ch] = Node(ch)
curr = curr.children[ch]
curr.is_end = True

def search(self, word: str) -> bool:
curr = self.head

for ch in word:
if ch not in curr.children:
return False
curr = curr.children[ch]

return curr.is_end

def startsWith(self, prefix: str) -> bool:
curr = self.head

for ch in prefix:
if ch not in curr.children:
return False
curr = curr.children[ch]
return True

0 comments on commit 3e2c6d9

Please sign in to comment.