Last active
August 28, 2019 03:03
-
-
Save xplorld/7844896fd51dc4cf57766d936ca45683 to your computer and use it in GitHub Desktop.
leetcode-safe trie
This file contains hidden or 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
import collections | |
class Trie: | |
def __init__(self): | |
self.children = collections.defaultdict(Trie) | |
self.is_leaf = False | |
def add(self, string): | |
if string == '': | |
self.is_leaf = True | |
else: | |
head = string[0] | |
tail = string[1:] | |
self.children[head].add(tail) | |
def contains(self, string): | |
if string == '': | |
return self.is_leaf | |
else: | |
head = string[0] | |
tail = string[1:] | |
return self.children[head].contains(tail) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
?