Implement_Trie_(Prefix_Tree)
来源:互联网 发布:淘宝直通车怎么样 编辑:程序博客网 时间:2024/06/05 20:41
题目描述:
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 Implement_Trie_Prefix_Tree {public static void main(String[] args) {Trie obj = new Trie();obj.insert("abc");obj.insert("acd");obj.insert("blue");obj.insert("boot");obj.insert("broun");obj.insert("cat");obj.insert("course");System.out.println(obj.search("abc"));System.out.println(obj.search("acc"));System.out.println(obj.startsWith("ac"));System.out.println(obj.startsWith("boo"));System.out.println(obj.startsWith("ba"));}}class Trie { //总根节点 private TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ //插入操作:自上向下扫描树,如果有该节点那么就继续向下,如果没有那么就新建一个。 public void insert(String word) { HashMap<Character, TrieNode> children = root.children; char array[] = word.toCharArray(); for(int i=0;i<array.length;i++) { char chr = array[i]; TrieNode node; if(children.containsKey(chr)) { node = children.get(chr); } else { node = new TrieNode(chr); children.put(chr,node); } children = node.children; //将最后一个节点设置为叶子结点 if(i==array.length-1) node.isLeaf = true; } } /** Returns if the word is in the trie. */ public boolean search(String word) { //如果存在这条路径且最后一个字母为叶子结点那么存在这个word if(SearchNode(word)!=null&&SearchNode(word).isLeaf) return true; return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { //如果存在word这条这条分支那么有以word开头的分支 if(SearchNode(prefix)!=null) return true; return false; } //搜索自顶向下存不存在word这条分支 public TrieNode SearchNode(String word) { HashMap<Character, TrieNode> children = root.children; TrieNode node = null; char array[] = word.toCharArray(); //一路向下搜索,如果有一个节点不存在那么便不存在这条分支 for(int i=0;i<array.length;i++) { if(children.containsKey(array[i])) { node = children.get(array[i]); children = node.children; } else { return null; } } return node; }}//节点类class TrieNode{//该节点的值char value;//该点的所有子节点HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();//是否为叶子结点boolean isLeaf;//总根节点不能有值public TrieNode(){}public TrieNode(char value){this.value = value;}}
本题还有一个升级版:Add_and_Search_Word_Data_structure_design
阅读全文
1 0
- Implement_Trie_(Prefix_Tree)
- 思维:分析框架化,模型化
- error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http:/
- 函数声明和函数表达式区别
- mysql优化系列02--(存储引擎选择)
- Libpcap库编程指南--数据包捕获
- Implement_Trie_(Prefix_Tree)
- 在Windows 7/10系统下如何安装TensorFlow GPU版
- 反射的学习笔记
- Java语法基础练习题2
- oracle 用户管理(一)
- Android ScrollView .顶部栏滑动透明度改变,底部栏滑到特定位置显示或隐藏效果
- 作业3:求1+2!+3!+...+20!的和
- 访问修饰符(一)
- 2017.9.10 机房模拟赛