|
| 1 | +# Design Add and Search Words Data Structure |
| 2 | +# https://leetcode.com/problems/design-add-and-search-words-data-structure/ |
| 3 | + |
| 4 | +class Node(object): |
| 5 | + def __init__(self): |
| 6 | + self.value = None |
| 7 | + # key: letter value: node |
| 8 | + self.next = {} |
| 9 | + self.eow = False |
| 10 | + |
| 11 | +class Trie(object): |
| 12 | + def __init__(self): |
| 13 | + self.head = Node() |
| 14 | + |
| 15 | + def createNode(self, value): |
| 16 | + node = Node() |
| 17 | + node.value = value |
| 18 | + return node |
| 19 | + |
| 20 | + def add(self, word, index, node): |
| 21 | + if (index == len(word)): |
| 22 | + node.eow = True |
| 23 | + return |
| 24 | + # if letter not in node next |
| 25 | + if (word[index] not in node.next): |
| 26 | + newNode = self.createNode(word[index]) |
| 27 | + node.next[word[index]] = newNode |
| 28 | + # move on to next letter |
| 29 | + self.add(word, index+1, node.next[word[index]]) |
| 30 | + |
| 31 | + def addWord(self, word): |
| 32 | + self.add(word, 0, self.head) |
| 33 | + self.display(self.head, []) |
| 34 | + |
| 35 | + def display(self, node, words): |
| 36 | + if node.eow: |
| 37 | + print "".join(words) |
| 38 | + for key in node.next: |
| 39 | + self.display(node.next[key], words+[key]) |
| 40 | + |
| 41 | + def searchWord(self, word): |
| 42 | + return self.search(self.head, word, 0) |
| 43 | + |
| 44 | + def search(self, node, word, index): |
| 45 | + if (index == len(word)): |
| 46 | + if (node.eow): |
| 47 | + return True |
| 48 | + return False |
| 49 | + #print "checking", word[index] |
| 50 | + if (word[index] != "." and (word[index] not in node.next)): |
| 51 | + return False |
| 52 | + # dot can match any character |
| 53 | + if (word[index] == "."): |
| 54 | + for key in node.next: |
| 55 | + if(self.search(node.next[key], word, index+1)): |
| 56 | + return True |
| 57 | + else: |
| 58 | + return self.search(node.next[word[index]], word, index+1) |
| 59 | + |
| 60 | + |
| 61 | +class WordDictionary(object): |
| 62 | + |
| 63 | + def __init__(self): |
| 64 | + self.trie = Trie() |
| 65 | + """ |
| 66 | + Initialize your data structure here. |
| 67 | + """ |
| 68 | + |
| 69 | + |
| 70 | + def addWord(self, word): |
| 71 | + self.trie.addWord(word) |
| 72 | + """ |
| 73 | + :type word: str |
| 74 | + :rtype: None |
| 75 | + """ |
| 76 | + |
| 77 | + |
| 78 | + def search(self, word): |
| 79 | + return self.trie.searchWord(word) |
| 80 | + """ |
| 81 | + :type word: str |
| 82 | + :rtype: bool |
| 83 | + """ |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | +# Your WordDictionary object will be instantiated and called as such: |
| 88 | +# obj = WordDictionary() |
| 89 | +# obj.addWord(word) |
| 90 | +# param_2 = obj.search(word) |
0 commit comments