[LintCode]Add and Search Word

本文介绍了一种使用Trie树(前缀树)的数据结构来实现单词字典的方法。该字典支持添加单词及搜索功能,其中搜索功能特别针对包含通配符‘.’的情况进行了优化处理。

数据结构如图所示:题目要求符合Trie树特征。在Trie树的设计上,每个节点包括一个大小为26的数组,用来保存当前的值,和一个布尔型变量用来确定是否

单词已经结束。下图为单词aa,ab的结构图:


public class WordDictionary {
    TrieNode tree = new TrieNode();
    // Adds a word into the data structure.
    public void addWord(String word) {
        if(search(word)) return;
        
        TrieNode root = tree;
        char[] chars = word.toCharArray();
        
        for(char c : chars) {
            if(root.arr[c - 'a'] == null) {
                TrieNode tmp = new TrieNode();
                root.arr[c - 'a'] = tmp;
                root = tmp;
            }
            else {
                root = root.arr[c - 'a'];
            }
        }
        root.isLeaf = true;//末尾添加leaf
        
    }
    
     public boolean search(String word) {
        return df(tree, word, 0);
     }

    // 使用index处理‘.’
    public boolean df(TrieNode root, String word, int index) {
        if(word.length() == index && root.isLeaf) return true;
        if(index >= word.length()) return false;
        
        char c = word.charAt(index);
        
        if(c == '.') {
            for(int i = 0; i < 26; i++) {
                if(root.arr[i] != null) {
                    if(df(root.arr[i], word, index + 1))
                    return true;
                }
            }
            return false;
        }
        
        if(root.arr[c - 'a'] != null) {
            return df(root.arr[c - 'a'], word, index + 1);
        }
        else 
            return false;
    }
    
    class TrieNode{
        TrieNode[] arr;
        boolean isLeaf;
     
        public TrieNode(){
            arr = new TrieNode[26];
        }    
    }
}



// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值