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
Note:
You may assume that all words are consist of lowercase letters a-z.
Trie 總結(jié): http://www.reibang.com/p/357c1dbe31ec
Solution:Trie
思路: Trie基本套路 + "."跳過(guò)
1a: Iterative serach解法
1b: recursive search解法
Time Complexity: O(word_num * word_len)
Space Complexity: O(number of nodes)
Solution1a Code:
public class WordDictionary {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
}
private TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(cur.children[c - 'a'] == null){
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
public boolean search(String word) {
return search_helper(word, 0, root);
}
public boolean search_helper(String word, int start, TrieNode cur_node) {
TrieNode cur = cur_node;
for(int i = start; i < word.length(); i++) {
char c = word.charAt(i);
if(c == '.') {
for (int child = 0; child < cur.children.length; child++) {
if (cur.children[child] != null && search_helper(word, i + 1, cur.children[child])) {
return true;
}
}
return false;
}
else {
if(cur.children[c - 'a'] == null) return false;
cur = cur.children[c - 'a'];
}
}
return cur.isWord;
}
}
Solution1b Code:
public class WordDictionary {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
}
private TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(cur.children[c - 'a'] == null){
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
public boolean search(String word) {
return search_helper(word, 0, root);
}
public boolean search_helper(String word, int start, TrieNode cur_node) {
TrieNode cur = cur_node;
for(int i = start; i < word.length(); i++) {
char c = word.charAt(i);
if(c == '.') {
for (int child = 0; child < cur.children.length; child++) {
if (cur.children[child] != null && search_helper(word, i + 1, cur.children[child])) {
return true;
}
}
return false;
}
else {
return cur.children[c - 'a'] != null && search_helper(word, start + 1, cur.children[c - 'a']);
}
}
return cur.isWord;
}
}