classTrie{privateclassTrieNode{boolean isEnd;TrieNode[] next;TrieNode(){isEnd =false;next =newTrieNode[26];}}privateTrieNode root;/** Initialize your data structure here. */publicTrie(){root =newTrieNode();}/** Inserts a word into the trie. */// 没则插,结尾改 true (出现了,但是没真正 insert 的话,不算:比如 insert apple , 然后 search app = falsepublicvoidinsert(String word){char[] wordC = word.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){// error:TrieNode nextNode = nowNode.next[wordC[i] - 'a']; nextNode = new TrieNode()// 会直接丢失引用!int index = wordC[i]-'a';if(nowNode.next[index]==null){nowNode.next[index]=newTrieNode();}nowNode = nowNode.next[index];}// 结束,标志单词结尾字符nowNode.isEnd =true;}/** Returns if the word is in the trie. */publicbooleansearch(String word){char[] wordC = word.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){int index = wordC[i]-'a';if(nowNode.next[index]==null){returnfalse;}nowNode = nowNode.next[index];}return nowNode.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix){char[] wordC = prefix.toCharArray();TrieNode nowNode = root;for(int i =0; i < wordC.length; i++){int index = wordC[i]-'a';if(nowNode.next[index]==null){returnfalse;}nowNode = nowNode.next[index];}returntrue;}}/*** 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);*/
更新版
其实三个函数的代码都差不多= =
前缀树:存储字符串的一种树结构(二十六叉树),可以实现拼写检查、自动补全功能。
classTrie{TrieNode root;privateclassTrieNode{boolean isEnd;TrieNode[] nextNode;publicTrieNode(){isEnd =false;nextNode =newTrieNode[26];}}publicTrie(){root =newTrieNode();}publicvoidinsert(String word){TrieNode nowNode = root;for(char c : word.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){nowNode.nextNode[index]=newTrieNode();}nowNode = nowNode.nextNode[index];}nowNode.isEnd =true;}publicbooleansearch(String word){TrieNode nowNode = root;for(char c : word.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){returnfalse;}nowNode = nowNode.nextNode[index];}return nowNode.isEnd;}publicbooleanstartsWith(String prefix){TrieNode nowNode = root;for(char c : prefix.toCharArray()){int index = c -'a';if(nowNode.nextNode[index]==null){returnfalse;}nowNode = nowNode.nextNode[index];}returntrue;}}
1M等于多少字节?以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!1M等于多少字节?不是1M等于多少字节,是1MB等于多少字节。字节(Byte /bait/ n. [C])是计算机信息技术用于计量存…
文章目录题目描述思路 & 代码题目描述
挺简单的,直接看思路代码吧。
思路 & 代码
就是一个层序遍历,取每层的最右边结点即可
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* T…