美文网首页
208. Implement Trie (Prefix Tree

208. Implement Trie (Prefix Tree

作者: FlynnLWang | 来源:发表于2016-12-26 05:04 被阅读0次

    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

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

    相关文章

      网友评论

          本文标题:208. Implement Trie (Prefix Tree

          本文链接:https://www.haomeiwen.com/subject/stadvttx.html