标签:
insert
, search
, and startsWith
methods.Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Subscribe to see which companies asked this question
class TrieNode { public HashMap<Character, TrieNode> children = new HashMap<>(); public boolean exist = false; public TrieNode() { } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { TrieNode r = root; for(int i = 0; i<word.length(); ++i) { Character c = word.charAt(i); TrieNode child = r.children.get(c); if(child == null) { child = new TrieNode(); r.children.put(c, child); } r = child; } r.exist = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode r = root; for(int i = 0; i<word.length(); ++i) { Character c = word.charAt(i); TrieNode child = r.children.get(c); if(child == null) return false; r = child; } return r.exist; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode r = root; for(int i = 0; i<prefix.length(); ++i) { Character c = prefix.charAt(i); TrieNode child = r.children.get(c); if(child == null) return false; r = child; } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
208. Implement Trie (Prefix Tree)
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5541081.html