208. Implement Trie (Prefix Tree)

Question

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

Code

class TrieNode {
    public Map<Character, TrieNode> sons;
    public char c;
    public boolean end;
    // Initialize your data structure here.
    public TrieNode() {
        sons = new HashMap<>();
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        if (word == null || word.length() == 0) return;
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!node.sons.containsKey(c)) {
                TrieNode newSon = new TrieNode();
                newSon.c = c;
                node.sons.put(c, newSon);
            }
            node = node.sons.get(c);
        }
        node.end = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        if (word == null || word.length() == 0) return true;
        TrieNode node = root;
        
        boolean re = false;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.sons.containsKey(c)) {
                node = node.sons.get(c);
            } else {
                return false;
            }
        }
        if (node.end) re = true;
        return re;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if (prefix == null || prefix.length() == 0) return true;
        TrieNode node = root;
        
        boolean re = false;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (node.sons.containsKey(c)) {
                node = node.sons.get(c);
            } else {
                return false;
            }
        }
        re = true;
        return re;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

Solution

实现一颗字典树。 常规方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容