|
| 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 | + |
0 commit comments