此题是字典树的应用

字典树(Trie树),是一种利用字符的单个匹配来实现树的一层层遍历,利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
它有3个基本性质:
根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。
在此题中,因为添加了一个‘.’的匹配,查找起来比平时的单词查找麻烦一点,直接见代码如下。
class WordDictionary {
private int SIZE = 26;
private TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
}
public class TrieNode{
private int num;//记录经过该节点的个数
private TrieNode[] son;
private boolean isEnd;//判断记录的单词是不是已经到了末尾
private char val;
TrieNode()
{
num = 1;
son = new TrieNode[26];//每个节点的子树
isEnd = false;
}
}
/** Adds a word into the data structure. */
public void addWord(String word) {
if(word.length()==0 || word == null)
return;
TrieNode Node = root;
char[] str = word.toCharArray();
for(int i = 0; i< word.length();i++)
{
int pos = str[i] - 'a';
if(Node.son[pos] == null)
{
Node.son[pos] = new TrieNode();
Node.son[pos].val = str[i];
}
else
{
Node.son[pos].num++;
}
Node = Node.son[pos];
}
Node.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) {
if(word == null || word.length()==0)
return false;
TrieNode Node = root;
char[] str = word.toCharArray();
return dfs(root,str,0,word.length());//dfs查找匹配
}
public boolean dfs(TrieNode Node, char[] str, int i,int len)
{
if(len==i)
{
if(Node.isEnd)
return true;
else
return false;
}
int pos=-1;
if(str[i]!='.')//‘.’是一个特例,没有这行,会数组越界
pos= str[i] -'a';
if(pos!=-1&&Node.son[pos] != null&&Node.son[pos].val == str[i])
{
return dfs(Node.son[pos],str,i+1,len);
}
else if(str[i] == '.')
{
for(int j = 0; j< 26;j++)
{
if(Node.son[j]!=null)
if(dfs(Node.son[j],str,i+1,len)) return true;//因为'.'可以匹配任意字符,所以只要出现匹配一次就好
}
}
else
{
return false;
}
return false;
}
}

这篇博客介绍了如何利用字典树解决LeetCode 211问题,重点在于处理'.'通配符的查找策略。文章详细阐述了字典树的基本性质,并提供了Java实现的代码示例。

508

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



