leetcode 211 Add and Search Word - Data structure design
z

Design a data structure that supports the following two operations:

1
2
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:

1
2
3
4
5
6
7
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.


  • 可以使用trie数来处理
  • 主要是处理.的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class WordDictionary {
class Node {
Node[] next;
boolean isWord;

public Node() {
next = new Node[26];
};
}

Node root = new Node();

/** Initialize your data structure here. */
public WordDictionary() {
}

/** Adds a word into the data structure. */
public void addWord(String word) {
Node p = root;
for (char c: word.toCharArray()) {
if (p.next[c-'a'] == null) {
p.next[c-'a'] = new Node();
}
p = p.next[c-'a'];
}
p.isWord = true;
}

/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return find(word, root);
}

public boolean find(String word, Node p) {
for (int i=0; i<word.length(); i++) {
char c = word.charAt(i);
if (c>='a' && c<='z') {
if (p.next[c-'a'] == null) {
return false;
}
p = p.next[c-'a'];
}
else {
boolean find = false;
for (Node n: p.next) {
if (n != null) {
find = (find || find(word.substring(i+1), n));
}
}
return find;
}
}
return p.isWord;
}
}

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/