class TrieNode { // Initialize your data structure here. HashMapchildren = new HashMap (); boolean isWord = false; char currentChar; public TrieNode() { } public TrieNode(char in){ currentChar = in; } public void addChild(char kid){ if (children.containsKey(kid)){ return; } children.put(kid, new TrieNode(kid)); } public boolean hasChild(char kid){ return children.containsKey(kid); } public TrieNode getChild(char kid){ if (!hasChild(kid)){ return null; } return children.get(kid); } public boolean isNodeWordEnd(){ return isWord; } public void setNodeAWordEnd(){ isWord = true; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++){ char temp = word.charAt(i); if (!node.hasChild(temp)){ node.addChild(temp); } node = node.getChild(temp); } node.setNodeAWordEnd(); } // Returns if the word is in the trie. public boolean search(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++){ char temp = word.charAt(i); if (!node.hasChild(temp)){ return false; } node = node.getChild(temp); } return node.isNodeWordEnd(); } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode node = root; for (int i = 0; i < prefix.length(); i++){ char temp = prefix.charAt(i); if (!node.hasChild(temp)){ return false; } node = node.getChild(temp); } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
Tuesday, October 20, 2015
[leetcode] Implement Trie (Prefix Tree)
没什么好说的。code非常直观
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment