您的位置:首页 > 其它

Leetcode 211. Add and Search Word - Data structure design

2016-06-22 09:27 543 查看


211. Add and Search Word - Data structure design

Total Accepted: 26865 Total
Submissions: 132696 Difficulty: Medium

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 
.
.
.
 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
.
click to show hint.
You should be familiar with how a Trie works. If not, please work on this problem: Implement
Trie (Prefix Tree) first.

在下午刚写完208之后,默默写了这个题。

第一次没有任何check submit直接AC,感觉很爽。

思路跟208差不多,就是多了个.万能适配符,碰到则遍历所有child节点,有满足条件的return true就行了。

public class WordDictionary { // 22ms
TrieNode root;

public WordDictionary(){
this.root = new TrieNode();
}

// Adds a word into the data structure.
public void addWord(String word) {
if(word.length()==0) return;
char[] words = word.toCharArray();
root.insert(words, 0);
}

// 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) {
if(word.length()==0) return true;
char[] words = word.toCharArray();
return root.search(words, 0);
}

class TrieNode{
char label;
TrieNode[] child;
boolean isWord;

public TrieNode(){
this.label = 'R';
this.child = new TrieNode[26];
this.isWord = false;
}

public TrieNode(char label){
this.label = label;
this.child = new TrieNode[26];
this.isWord = false;
}

public void insert(char[] words, int cur){
int pos = words[cur] - 'a';
if(child[pos] == null) child[pos] = new TrieNode(words[cur]);
if(cur == words.length-1){
child[pos].isWord = true; return;
}
child[pos].insert(words, cur + 1);
}

public boolean search(char[] words, int cur){
if(cur == words.length-1){
if(words[cur] == '.'){
for(int i = 0; i < 26; i++){
if(child[i] != null && child[i].isWord == true) return true;
}
return false;
}else{
int pos = words[cur] - 'a';
if(child[pos] != null && child[pos].isWord == true) return true;
return false;
}
}

if(words[cur] == '.'){
for(int i = 0; i < 26; i++){
if(child[i] == null) continue;
if(child[i].search(words, cur + 1)) return true;
}
return false;
}else{
int pos = words[cur] - 'a';
if(child[pos] == null) return false;
return child[pos].search(words, cur + 1);
}
}
}
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Trie Design