211. Add and Search Word - Data structure design

Posted Premiumlab

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了211. Add and Search Word - Data structure design相关的知识,希望对你有一定的参考价值。

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

 

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.

For 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.

 

 

Sol:

 

Use dictionary data structure to solve this problem.

 

The key is the lengh of word, and the word itself is the value. However, if two words have the same length, the keys will clash. To avoid this,  we use defaultdict from collections and we use append method to add new element to the dictionary.  

 

To implement the search method, we check if the input word is in the dictionary. 

 

 

class WordDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.word_dict = collections.defaultdict(list)
        

    def addWord(self, word):
        """
        Adds a word into the data structure.
        :type word: str
        :rtype: void
        """
        if word:
            self.word_dict[len(word)].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
        """
        
        if not word:
            return False
        if . not in word:
            return word in self.word_dict[len(word)]
        
        # if ‘.‘ is in the word
        for v in self.word_dict[len(word)]:
            for i, ch in enumerate(word):
                if ch != v[i] and ch != .:
                    break
            else:
                return True
        return False


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

 

 

 

 

Note:

 

1 for - else usage in python:

 

The else part is executed when for loop does not break. 

 

2 collections.defaultdic usage in python:

import collections
word_dict = collections.defaultdict(list)
word_dict[3].append("pad")
word_dict[3].append("dad")
print "pad" in word_dict[3]
print word_dict[3]

 

 

== >

 

True

[‘pad‘, ‘dad‘]

 

3 for i, ch in enumerate(word) usage in python:

 

Since we will check if word is in the dictionary with same key/length, it is natural to use enumerate. 

 

1 seq = [one, two, three]
2 for i, element in enumerate(seq):
3     print i, seq[i]

 

 

==>

0 one

1 two

2 three

 

 

Sol 2:

 

Use tree data structure. 

 

https://discuss.leetcode.com/topic/14216/tree-solutions-18-20-lines

 

https://discuss.leetcode.com/topic/26944/python-solution-recursive-version-dfs

 

https://discuss.leetcode.com/topic/23695/python-easy-to-follow-solution-using-trie

 

以上是关于211. Add and Search Word - Data structure design的主要内容,如果未能解决你的问题,请参考以下文章

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design