標籤:
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
解題思路:
參考百度百科:Trie樹
已經給出了詳細的代碼:
JAVA實現如下:
class TrieNode {// Initialize your data structure here.int num;// 有多少單詞通過這個節點,即節點字元出現的次數TrieNode[] son;// 所有的兒子節點boolean isEnd;// 是不是最後一個節點char val;// 節點的值TrieNode() {this.num = 1;this.son = new TrieNode[26];this.isEnd = false;}}public class Trie {private TrieNode root;public Trie() {root = new TrieNode();}public void insert(String word) {if (word == null || word.length() == 0)return;TrieNode node = this.root;char[] letters = word.toCharArray();for (int i = 0; i < word.length(); i++) {int pos = letters[i] - ‘a‘;if (node.son[pos] == null) {node.son[pos] = new TrieNode();node.son[pos].val = letters[i];} else {node.son[pos].num++;}node = node.son[pos];}node.isEnd = true;}// Returns if the word is in the trie.public boolean search(String word) {if (word == null || word.length() == 0) {return false;}TrieNode node = root;char[] letters = word.toCharArray();for (int i = 0; i < word.length(); i++) {int pos = letters[i] - ‘a‘;if (node.son[pos] != null) {node = node.son[pos];} else {return false;}}return node.isEnd;}// 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 false;}TrieNode node = root;char[] letters = prefix.toCharArray();for (int i = 0; i < prefix.length(); i++) {int pos = letters[i] - ‘a‘;if (node.son[pos] != null) {node = node.son[pos];} else {return false;}}return true;}}// Your Trie object will be instantiated and called as such:// Trie trie = new Trie();// trie.insert("somestring");// trie.search("key");
Java for LeetCode 208 Implement Trie (Prefix Tree)