208. Implement Trie (Prefix Tree) & 211. Add and Search Word

208. Implement Trie (Prefix Tree)arrow-up-right

Implement a trie with insert, search, and startsWith methods.

Note: You may assume that all inputs are consist of lowercase letters a-z.

My Solutions:

boolean end 的作用是标记此TrieNode到此结束,后面不再连着TrieNode了。search的时候需要找到end的单词。

class TrieNode {
    public TrieNode[] children;
    public boolean end;
    
    public TrieNode() {
        this.children = new TrieNode[26];
    }
}

public class Trie {
    
    private TrieNode root;
    
    /** Initialize your data structure here. */
    public Trie() {
        this.root = new TrieNode();
        root.end = true;
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode tn = root;
        for (char c : word.toCharArray()) {
            if (tn.children[c - 'a'] == null) tn.children[c - 'a'] = new TrieNode();
            tn = tn.children[c - 'a']; //set tn to be the current tn's child
        }
        tn.end = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode tn = root;
        for (char c : word.toCharArray()) {
            if (tn.children[c - 'a'] == null) return false;
            tn = tn.children[c - 'a'];
        }
        return tn.end; //确定这个单词存在,而不是其他单词的一部分
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode tn = root;
        for (char c : prefix.toCharArray()) {
            if (tn.children[c - 'a'] == null) return false;
            tn = tn.children[c - 'a'];
        }
        return true; //确定这个单词中每个字母都找到即可,可以是其他单词的一部分
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

211. Add and Search Wordarrow-up-right

Design a data structure that supports the following two operations:

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

Note: You may assume that all words are consist of lowercase letters a-z.

My Solutions:

和上题相同,在search 的时候,加入backtracking的思想

Last updated