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
思路:
如果去掉了特殊字符.就是一道典型的trie树解法题目,所以关键是如何解决特殊字符.的情况。
自己第一次想的是,每次add一个字符的时候同样add一个.字符,即把.当做第27个字符来看待,但是增加第一个.字符之后,如何解决后续字符在.节点的分支是个问题,同样在搜索的方法实现上也很复杂,自己没有想清楚怎么解决。
因此另一种实现方法,就是暴力的,如果遇见了.,则在当前节点的所有子节点进行搜索,如果字符串很长,并且trie树很茂盛,时间复杂度会很高,但是被accepted了!
class WordDictionary {
class TrieNode {
public boolean isWord;
public TrieNode[] children;
public TrieNode() {
this.isWord = false;
this.children = new TrieNode[26];
}
}
TrieNode root;
public WordDictionary() {
this.root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode dummy = this.root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (dummy.children[c - 'a'] == null) {
dummy.children[c - 'a'] = new TrieNode();
}
dummy = dummy.children[c - 'a'];
}
dummy.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 this._searchHelper(word, 0, this.root);
}
private boolean _searchHelper(String word, int pos, TrieNode node) {
if (pos == word.length()) {
return node.isWord;
}
char c = word.charAt(pos);
if (word.charAt(pos) != '.') {
if (node.children[c - 'a'] == null) {
return false;
}
return _searchHelper(word, pos + 1, node.children[c - 'a']);
} else {
for (int i = 0; i < 26; i++) {
if (node.children[i] != null && _searchHelper(word, pos + 1, node.children[i])) {
return true;
}
}
return false;
}
}
}