leetcode-add-and-search-word

题目大意

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

  实现高效的方法,能够支持频繁插入和搜索字符串,注意搜索字符串可能有.进行模糊匹配

题目分析

  很明显利用trie树(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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class TrieNode {
public char ch;
public int freq;
public TrieNode[] child;
public TrieNode() {
child = new TrieNode[26];
}
}
class Trie {
public TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
char[] w = word.toCharArray();
int len = w.length;
TrieNode cur = root;
for (int i = 0; i < len; i++) {
if (cur.child[w[i] - 'a'] == null) {
cur.child[w[i] - 'a'] = new TrieNode();
cur = cur.child[w[i] - 'a'];
cur.ch = w[i];
} else {
cur = cur.child[w[i] - 'a'];
}
if (i == len - 1) {
cur.freq++;
}
}
}
public boolean searchReg(String word, int idx, TrieNode r) {
if (idx > word.length() - 1) {
if (r.freq > 0) {
return true;
}
return false;
}
if (r == null || r.child == null) {
return false;
}
char w = word.charAt(idx);
if (w != '.') {
if (r.child[w - 'a'] != null) {
return searchReg(word, idx + 1, r.child[w - 'a']);
}
} else {
for (int i = 0; i < 26; i++) {
if (r.child[i] != null && searchReg(word, idx + 1, r.child[i])) {
return true;
}
}
}
return false;
}
}
public class WordDictionary {
private Trie trie;
/** Initialize your data structure here. */
public WordDictionary() {
trie = new Trie();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
trie.insert(word);
}
/** 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 trie.searchReg(word, 0, trie.root);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/