欢迎大家来到IT世界,在知识的湖畔探索吧!
欢迎大家来到IT世界,在知识的湖畔探索吧!
根据Trie树的属性,我们给出简单的Trie树创建·和查找的代码示例:
package com.quan.trie; public class Trie { // root for current trie TreeNode root; // define the TreeNode class TreeNode{ // children of current node. TreeNode[] children; // whether is end of a word. boolean isEnd; //Assume that there are only lowercase letters in the word public TreeNode (){ children = new TreeNode[26]; } } / Initialize your data structure here. */ public Trie() { // Initialize the root without value. root = new TreeNode(); } / Inserts a word into the trie. */ public void insert(String word) { if (word == null || word.length() < 1) return; TreeNode node = root; for (int i = 0, pos = 0; i < word.length(); i++, node = node.children[pos]) { pos = word.charAt(i) - 'a'; if (node.children[pos] == null){ node.children[pos] = new TreeNode(); } } node.isEnd = true; } / Returns if the word is in the trie. */ public boolean search(String word) { if (word == null || word.length() < 1) return false; TreeNode node = root; for (int i = 0, pos = 0; i < word.length(); i++, node = node.children[pos]) { pos = word.charAt(i) - 'a'; if (node.children[pos] == null){ 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() < 1) return true; TreeNode node = root; for (int i = 0, pos = 0; i < prefix.length(); i++, node = node.children[pos]) { pos = prefix.charAt(i) - 'a'; if (node.children[pos] == null){ return false; } } return true; } }
欢迎大家来到IT世界,在知识的湖畔探索吧!
Trie树可以最大限度地减少无谓的字符串比较,在Trie树中对单个长度为的单词的查找时间复杂度可以做到
,且跟语料库中单词的数量没有太大关系。Trie树的使用场景主要有字符串检索、字符串字典排序、和前缀索引等。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/118446.html