20170602-leetcode-211-Add and Search Word

来源:互联网 发布:网络婚恋金融诈骗 编辑:程序博客网 时间:2024/06/06 02:23

1.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
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") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("b..") -> true

解读

2.Solution

class WordDictionary(object):    def __init__(self):        self.word_dict = collections.defaultdict(list)    def addWord(self, word):        if word:            self.word_dict[len(word)].append(word)    def search(self, word):        if not word:            return False        if '.' not in word:            return word in self.word_dict[len(word)]        for v in self.word_dict[len(word)]:            # match xx.xx.x with yyyyyyy            for i, ch in enumerate(word):                if ch != v[i] and ch != '.':                    break            #这里的结构为for-if-else,else跟for是同一个层次,当for循环遍历完所有的条件或者(for)条件不满足,而不是if语句中break导致循环的中止,执行else语句            else:                return True        return False

3.for -if -break-else的例子

>>> for n in range(2, 10):...     for x in range(2, n):...         if n % x == 0:...             print n, 'equals', x, '*', n/x...             break...     else:...         # loop fell through without finding a factor...         print n, 'is a prime number'...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3
原创粉丝点击