标签:26 前缀 Trie isEnd 节点 children
208. 实现 Trie (前缀树) - 力扣(LeetCode) (leetcode-cn.com)
前缀树(字典树) 是一种多叉树结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查
每个节点存放两个信息:
- chidren 是一个大小为 26 的一维数组,分别对应了26个英文字符 'a' ~ 'z',也就是说形成了一棵 26叉树
- isEnd 判断树的根节点到当前节点是否构成了一个单词
class Trie { private Trie[] children; private boolean isEnd; public Trie() { children = new Trie[26]; // 只是定义了一下,没有实例化,相当于树枝在那儿,但是没有链接节点 isEnd = false; } public void insert(String word) { Trie node = this; for(int i=0; i<word.length(); i++){ char ch = word.charAt(i); int index = ch - 'a'; if(node.children[index] == null){ node.children[index] = new Trie(); } node = node.children[index]; } node.isEnd = true; //当前节点是最后一个 } public boolean search(String word) { Trie node = this; //创建一个Trie对象,即一个新的节点,给节点指向当前字典树的根节点 for(int i=0; i<word.length(); i++){ char ch = word.charAt(i); int index = ch - 'a'; if(node.children[index] == null){ //这个位置的节点是空的,那么就要重新创建 return false; } node = node.children[index]; // 将节点下移 } if(node.isEnd == true){ return true; }else { return false; } } public boolean startsWith(String prefix) { //判断前缀 Trie node = this; for(int i=0; i<prefix.length(); i++){ char ch = prefix.charAt(i); int index = ch-'a'; if(node.children[index] == null){ return false; } node = node.children[index]; } return true; } }
标签:26,前缀,Trie,isEnd,节点,children 来源: https://www.cnblogs.com/charonkk/p/15496924.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。