Last active
October 1, 2015 02:58
-
-
Save vivekn/1906905 to your computer and use it in GitHub Desktop.
Tries 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Trie(object): | |
def __init__(self): | |
self.children = {} | |
self.flag = False # Flag to represent that a word ends at this node | |
def add(self, char): | |
self.children[char] = Trie() | |
def insert(self, word): | |
node = self | |
for char in word: | |
if char not in node.children: | |
node.add(char) | |
node = node.children[char] | |
node.flag = True | |
def contains(self, word): | |
node = self | |
for char in word: | |
if char not in node.children: | |
return False | |
node = node.children[char] | |
return node.flag |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment