Actually we can do it using the trie data structure that we designed before.
Solution:
# T:O(min(n, h)) S:O(min(n, h)) class TrieNode: # Initialize your data structure here. def __init__(self): self.is_string = False self.leaves = {} class WordDictionary: def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Adds a word into the data structure. def addWord(self, word): curr = self.root for c in word: if not c in curr.leaves: curr.leaves[c] = TrieNode() curr = curr.leaves[c] curr.is_string = True # @param {string} word # @return {boolean} # Returns if the word is in the data structure. A word could # contain the dot character '.' to represent any one letter. def search(self, word): return self.searchHelper(word, 0, self.root) def searchHelper(self, word, start, curr): if start == len(word): return curr.is_string if word[start] in curr.leaves: return self.searchHelper(word, start+1, curr.leaves[word[start]]) elif word[start] == '.': for c in curr.leaves: if self.searchHelper(word, start+1, curr.leaves[c]): return True return FalseRun Time: 568 ms
No comments:
Post a Comment