
方法1: 和208题一样,都是trie数据结构。不是很难,直接上代码。
class TrieNode {
public char val;
public boolean isEnd;
public TrieNode[] children = new TrieNode[26];
public TrieNode(){}
TrieNode(char c){
this.val = c;
TrieNode node = new TrieNode();
}
}
class WordDictionary {
TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
this.root = new TrieNode(' ');
}
public void addWord(String word) {
TrieNode node = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(node.children[c - 'a'] == null){
node.children[c - 'a'] = new TrieNode(c);
}
node = node.children[c - 'a'];
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = root;
return helper(0, node, word);
}
public boolean helper(int start, TrieNode node, String word){
if(start == word.length()) return node.isEnd;
char c = word.charAt(start);
if(c == '.'){
boolean flag = true;
for(int j = 0; j < 26; j++){
if(node.children[j] != null){
flag = false;
if(helper(start + 1, node.children[j], word)) return true;
}
}
if(flag) return false;
}else{
if(node.children[c - 'a'] == null){
return false;
}else{
return helper(start + 1, node.children[c - 'a'], word);
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
总结:
- 无
1226

被折叠的 条评论
为什么被折叠?



