Trie 字典树

63 阅读1分钟
  1. 碰到那种单词题需要用trie 比如说211

211. Design Add and Search Words Data Structure

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

 

Example:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
class Trie{
    private Trie[] children;
    boolean isword;

    Trie() {
        children = new Trie[26];
        isword = false;
    }

    public void insert(String word) {
        Trie node = this;
        for(char ch: word.toCharArray()) {
            int index = ch - 'a';
            if(node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isword = true;
    }

    public boolean search(String word, Trie node, int indexofword) {
        if(indexofword == word.length()) {
            return node.isword;
        }
        char ch = word.charAt(indexofword);
        if(ch == '.') {
            for(int i = 0; i < 26; i++) {
                if(node.children[i] != null && search(word, node.children[i], indexofword+1)) {
                    return true;
                } 
            }
        } else {
            int index = ch - 'a';
            if(node.children[index] == null) {
                return false;
            }
            return search(word, node.children[index], indexofword + 1);
        }
        return false;
    }
}
class WordDictionary {   
    Trie trie;
    public WordDictionary() {
        trie = new Trie();
    }
    
    public void addWord(String word) {
        trie.insert(word);
    }
    
    public boolean search(String word) {
        return trie.search(word, trie, 0);
    }
}