Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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

My code:

import collections
class WordDictionary(object):
    def __init__(self):
        self.len2words = collections.defaultdict(list) 

    def addWord(self, word):
        self.len2words[len(word)].append(word)

    def search(self, word):
        words = self.len2words[len(word)]
        for i, char in enumerate(word):
            words = [w for w in words if char in ('.', w[i])]
            if not words: return False
        return True

class WordDictionary1(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dict={}

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        self.dict[word]=1
        

    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
        """
        if word in self.dict.keys():
            return True
        if '.' not in word:
            return False
        else:
            for item in self.dict.keys():
                if len(item)!=len(word):
                    continue
                flag=True
                for i in range(len(item)):
                    if word[i]=='.':
                        continue
                    if word[i]!=item[i]:
                        flag=False
                        break
                if flag:
                    return True
        return False
        


# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

Solution: https://leetcode.com/problems/add-and-search-word-data-structure-design/