-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesignAddandSearchWordsDataStructure.py
More file actions
49 lines (40 loc) · 1.31 KB
/
designAddandSearchWordsDataStructure.py
File metadata and controls
49 lines (40 loc) · 1.31 KB
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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/design-add-and-search-words-data-structure/
# Author: Miao Zhang
# Date: 2021-01-26
class TrieNode(object):
def __init__(self):
self.children = {}
self.is_word = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
def search(self, word: str) -> bool:
def dfs(node, i):
if i == len(word):
return node.is_word
if word[i] == '.':
for next_node in node.children.values():
if dfs(next_node, i + 1):
return True
else:
if word[i] in node.children:
if dfs(node.children[word[i]], i + 1):
return True
node = self.root
return dfs(node, 0)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)