[211] Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/description/
- algorithms
- Medium (27.94%)
- Source Code: 211.add-and-search-word-data-structure-design.py
- Total Accepted: 110.4K
- Total Submissions: 369.9K
- Testcase Example: '["WordDictionary","addWord","addWord","addWord","search","search","search","search"]\n[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]'
Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note: You may assume that all words are consist of lowercase letters a-z.
python
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.bag = {}
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
lenw = len(word)
if not lenw in self.bag:
self.bag[lenw] = []
self.bag[lenw].append(word)
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
lenw = len(word)
if lenw not in self.bag: return False
return any([self.equal_to(word, item) for item in self.bag[lenw]])
def equal_to(self, target, word):
if not len(target) == len(word): return False
for idx, c in enumerate(target):
if not c == '.' and not c == word[idx]:
return False
return True
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)