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 lettersa-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
Solution: 遇到“.”时,从a到z找
TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!cur.hashmap.containsKey(c)) {
cur.hashmap.put(c, new TrieNode());
}
cur = cur.hashmap.get(c);
}
cur.hasWord = 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 search_helper(word, root, 0);
}
private boolean search_helper(String word, TrieNode cur, int index) {
if (index == word.length()) {
return cur.hasWord;
}
char c = word.charAt(index);
if (c == '.') {
for (char a = 'a'; a <= 'z'; a++) {
//不能写成if (cur.hashmap.containsKey(a)) return search_helper(word, cur.hashmap.get(a), index + 1);
if (cur.hashmap.containsKey(a) && search_helper(word, cur.hashmap.get(a), index + 1)) {
return true;
}
}
return false;
} else if (cur.hashmap.containsKey(c)) {
return search_helper(word, cur.hashmap.get(c), index + 1);
} else {
return false;
}
}
class TrieNode {
boolean hasWord;
Map<Character, TrieNode> hashmap;
public TrieNode() {
hashmap = new HashMap<>();
hasWord = false;
}
}
或者:
class TrieNode{
TrieNode[] children;
boolean hasWord;
TrieNode(){
children = new TrieNode[26];
hasWord = false;
}
}
public void addWord(String word) {
TrieNode now = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(now.children[c - 'a'] == null){
now.children[c - 'a'] = new TrieNode();
}
now = now.children[c - 'a'];
}
now.hasWord = true;
}