Question
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
Code
class TrieNode {
public boolean end;
public TrieNode[] sons;
public TrieNode() {
end = false;
sons = new TrieNode[26];
}
}
class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String s) {
if (s.length() == 0) return;
TrieNode node = root;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (node.sons[c - 'a'] == null) {
TrieNode newSon = new TrieNode();
node.sons[c - 'a'] = newSon;
}
node = node.sons[c - 'a'];
}
node.end = true;
}
public boolean search(String s) {
if (s == null || s.length() == 0) return true;
return searchHelper(s, root, 0);
}
public boolean searchHelper(String s, TrieNode node, int i) {
if (i == s.length()) {
if (node.end) return true;
return false;
}
boolean result = false;
char c = s.charAt(i);
if (c == '.') {
for (int j = 0; j < 26; j++) {
if (node.sons[j] != null) {
if(searchHelper(s, node.sons[j], i + 1)) result = true;
}
}
} else {
if (node.sons[c - 'a'] == null) {
result = false;
} else {
if (searchHelper(s, node.sons[c - 'a'], i + 1)) result = true;
}
}
return result;
}
}
public class WordDictionary {
Trie t = new Trie();
// Adds a word into the data structure.
public void addWord(String word) {
t.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 t.search(word);
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
Solution
用字典树的insert()和search()实现。其中search()功能略做改动,当当前字符为‘.’时需遍历所有叶子节点,若叶子节点不为null则递归地search剩余部分。其他情况与正常的字典树相同。