题目链接:https://leetcode.com/problems/add-and-search-word-data-structure-design/
设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
思路:
用trie树来解决,不了解trie树的来传送门:传送门
然后题目中唯一的特殊点就是.可以代替任何字母,所匹配到.字符时,对后续的26个孩子节点进行遍历回溯即可。
AC
Runtime: 79 ms, faster than 81.21% of Java online submissions for Add and Search Word - Data structure design.
Memory Usage: 58.3 MB, less than 56.97% of Java online submissions forAdd and Search Word - Data structure design.
class TrieNode{
TrieNode[] children;
boolean isEnd;
public TrieNode(){
children =new TrieNode[26];
isEnd=false;
}
}
class WordDictionary {
TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root=new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode temp=root;
for(char c:word.toCharArray()){
if(temp.children[c-'a']==null){
temp.children[c-'a']=new TrieNode();
}
temp=temp.children[c-'a'];
}
temp.isEnd=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 helper(word,root,0);
}
public boolean helper(String word,TrieNode temp,int index){
if(temp==null)
return false;
if(index==word.length())
return temp.isEnd;
char c=word.charAt(index);
if(c!='.'){
if(temp.children[c-'a']==null)
return false;
else
return helper(word,temp.children[c-'a'],index+1);
}else{
for(TrieNode tn:temp.children){
if(helper(word,tn,index+1))
return true;
}
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);
*/