Skip to content

Commit e1dbcf5

Browse files
committed
Day 5 - Add and Search Word - Data structure design
1 parent 1601e8b commit e1dbcf5

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# -------------------------------------------------------
2+
# Add and Search Word - Data structure design - https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3413/
3+
# -------------------------------------------------------
4+
# Author: Arshad Mehmood
5+
# Github: https://github.com/arshad115
6+
# Blog: https://arshadmehmood.com
7+
# LinkedIn: https://www.linkedin.com/in/arshadmehmood115
8+
# Date : 2020-08-5
9+
# Project: leetcode-august-2020
10+
# -------------------------------------------------------
11+
import collections
12+
13+
14+
class WordDictionary:
15+
16+
def __init__(self):
17+
"""
18+
Initialize your data structure here.
19+
"""
20+
self.dict = collections.defaultdict(list)
21+
22+
def addWord(self, word: str) -> None:
23+
"""
24+
Adds a word into the data structure.
25+
"""
26+
if word:
27+
self.dict[len(word)].append(word)
28+
29+
def search(self, word: str) -> bool:
30+
"""
31+
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
32+
"""
33+
if not word:
34+
return False
35+
if '.' not in word:
36+
return word in self.dict[len(word)]
37+
else:
38+
for w in self.dict[len(word)]:
39+
for i, l in enumerate(word):
40+
if l!=w[i] and l!='.':
41+
break
42+
else:
43+
return True
44+
return False
45+
46+
# Your WordDictionary object will be instantiated and called as such:
47+
obj = WordDictionary()
48+
obj.addWord("bad")
49+
obj.addWord("dad")
50+
obj.addWord("mad")
51+
print(obj.search("pad"))
52+
print(obj.search("bad"))
53+
print(obj.search(".ad"))
54+
print(obj.search("b.."))
55+

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ My leetcode profile can be viewed [here](https://leetcode.com/arshad115/)
1010
| 2 | [Design Hashset](./codes/2-design-hashset.py) |
1111
| 3 | [Valid Palindrome](./codes/3-valid-palindrome.py) |
1212
| 4 | [Power of Four](./codes/4-valid-palindrome.py) |
13+
| 4 | [Add and Search Word - Data structure design](./codes/5-add-and-search-word-data-structure-design.py) |

0 commit comments

Comments
 (0)