-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path208_ImplementTrie.py
executable file
·58 lines (50 loc) · 1.47 KB
/
208_ImplementTrie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: [email protected]
# Refer to:
# https://leetcode.com/discuss/49529/my-python-solution
class TrieNode(object):
def __init__(self):
self.children = {}
self.is_word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
# Inserts a word into the trie.
cur_node = self.root
for ch in word:
if ch not in cur_node.children:
cur_node.children[ch] = TrieNode()
cur_node = cur_node.children[ch]
cur_node.is_word = True
def search(self, word):
# Returns if the word is in the trie.
cur_node = self.root
for ch in word:
if ch not in cur_node.children:
return False
cur_node = cur_node.children[ch]
return cur_node.is_word
def startsWith(self, prefix):
# Returns if there is any word in the trie
# that starts with the given prefix.
cur_node = self.root
for ch in prefix:
if ch not in cur_node.children:
return False
cur_node = cur_node.children[ch]
return True
"""
if __name__ == '__main__':
trie = Trie()
trie.insert("app")
trie.insert("apple")
trie.insert("beer")
trie.insert("add")
trie.insert("jam")
trie.insert("rental")
print trie.search("apps")
print trie.search("app")
print trie.search("ad")
"""