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

208. Implement Trie (Prefix Tree)

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 Word

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

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:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

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

My Solutions:

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

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

public class WordDictionary {
    
    private TrieNode root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        this.root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(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 data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
        TrieNode tn = root;
        return helper(root, word, 0);
    }
    
    private boolean helper(TrieNode root, String word, int pos) {
        if (pos == word.length()) return root.end;
        
        char c = word.charAt(pos);
        if (c == '.') {                
            for (int i = 0; i < root.children.length; i++) {
                if (root.children[i] != null) {
                    if (helper(root.children[i], word, pos + 1)) return true;
                }
            }
        } else {
            if (root.children[c - 'a'] != null) {
                return helper(root.children[c - 'a'], word, pos + 1);
            }
        } 
        
        return false;
    }
}

Last updated