leetcode-211-Add-and-Search-Word---Data-structure-design

描述


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(Java)


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
class WordDictionary {
TrieNode root;

/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
}

/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode current = root;
for (char c: word.toCharArray()) {
if (!current.children.containsKey(c)) {
current.children.put(c, new TrieNode());
}
current = current.children.get(c);
}
current.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 dfs(root, word);
}

boolean dfs(TrieNode root, String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c == '.') {
for (TrieNode n: current.children.values()) {
if (dfs(n, word.substring(i+1, word.length()))) {
return true;
}
}
return false;
} else if(!current.children.containsKey(c)) {
return false;
}
current = current.children.get(c);
}
return current.isWord;
}
}


class TrieNode {
boolean isWord = false;
Map<Character, TrieNode> children = new HashMap();
}

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

相关问题


题目来源