208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

题目含义:实现字典树的insertsearch, 和startsWith 方法

字典树概念参考http://blog.csdn.net/u012501459/article/details/46741267

Trie树的基本性质如下:

  • 根节点不包括字符,除根节点外每个节点包括一个字符。
  • 从根节点到某一节点,路径上经过的字符连接起来,即为对应的字符串。
  • 每个节点的所有子节点包含的字符串各不相同。

本题中的Trie树可以简单实现如下:

Trie树节点数据结构定义如下:

  1. val表示该节点对应的字符
  2. 子节点简单用一个数组表示,这样实现比较简单,但比较耗费内存
  3. isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。
复制代码
 1 class Trie {
 2     
 3     class TrieNode {
 4         public char val;
 5         public boolean isWord;
 6         public TrieNode[] children = new TrieNode[26];
 7         public TrieNode() {}
 8         TrieNode(char c){
 9             val = c;
10         }
11     }
12     
13     private TrieNode root;
14     /** Initialize your data structure here. */
15     public Trie() {
16         root = new TrieNode();
17         root.val = ' ';        
18     }
19     
20     /** Inserts a word into the trie. */
21     public void insert(String word) {
22         TrieNode ws = root;
23         for(int i = 0; i < word.length(); i++){
24             char c = word.charAt(i);
25             if(ws.children[c - 'a'] == null){
26                 ws.children[c - 'a'] = new TrieNode(c);
27             }
28             ws = ws.children[c - 'a'];
29         }
30         ws.isWord = true;        
31     }
32     
33     /** Returns if the word is in the trie. */
34     public boolean search(String word) {
35         TrieNode ws = root;
36         for(int i = 0; i < word.length(); i++){
37             char c = word.charAt(i);
38             if(ws.children[c - 'a'] == null) return false;
39             ws = ws.children[c - 'a'];
40         }
41         return ws.isWord;        
42     }
43     
44     /** Returns if there is any word in the trie that starts with the given prefix. */
45     public boolean startsWith(String prefix) {
46         TrieNode ws = root;
47         for(int i = 0; i < prefix.length(); i++){
48             char c = prefix.charAt(i);
49             if(ws.children[c - 'a'] == null) return false;
50             ws = ws.children[c - 'a'];
51         }
52         return true;        
53     }
54 }
复制代码

 

posted @   daniel456  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示