Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
public class Trie { Trie[] children; int count = 0; /** Initialize your data structure here. */ public Trie() { children = new Trie[26]; } /** Inserts a word into the trie. */ public void insert(String word) { if (word.equals("")) { count++; } Trie cur = this; int i = 0; while (i < word.length()) { if (cur.children[word.charAt(i) - ‘a‘] == null) { cur.children[word.charAt(i) - ‘a‘] = new Trie(); } cur = cur.children[word.charAt(i) - ‘a‘]; i++; } cur.count++; } /** Returns if the word is in the trie. */ public boolean search(String word) { Trie cur = this; int i = 0; while (cur != null && i < word.length()) { cur = cur.children[word.charAt(i) - ‘a‘]; i++; } if (cur == null || cur.count == 0) { return false; } return true; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { Trie cur = this; int i = 0; while (cur != null && i < prefix.length()) { cur = cur.children[prefix.charAt(i) - ‘a‘]; i++; } if (cur == null) { return false; } 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); */
208. Implement Trie (Prefix Tree)
原文:http://www.cnblogs.com/yuchenkit/p/7223486.html