208. Implement Trie (Prefix Tree)

 

创一个root node, 不用什么值, TrieNode要有一个26到数组记录每个字母存不存在,再来一个isWord给每个node判断一下是不是一个word(单词最后一个node才是一个word)

 

 1 class Trie {
 2     class TrieNode{
 3         boolean isWord;
 4         TrieNode[] children = new TrieNode[26];
 5      
 6     }
 7     TrieNode root = new TrieNode();
 8 
 9     /** Initialize your data structure here. */
10     public Trie() {
11             
12     }
13     
14     /** Inserts a word into the trie. */
15     public void insert(String word) {
16         TrieNode node = root;
17         for(int i = 0; i < word.length(); i++){
18             char c = word.charAt(i);
19             if(node.children[c - 'a'] != null){
20                 node = node.children[c - 'a'];
21             }else{
22                 node.children[c - 'a'] = new TrieNode();
23                 node = node.children[c - 'a'];
24             }
25         }
26         node.isWord = true;
27         
28     }
29     
30     /** Returns if the word is in the trie. */
31     public boolean search(String word) {
32         TrieNode node = root;
33         for(int i = 0; i < word.length(); i++){
34             char c = word.charAt(i);
35             if(node.children[c - 'a'] == null){
36                 return false;
37             }else{
38                 node = node.children[c - 'a'];
39             }
40             
41         }
42         return node.isWord;
43         
44     }
45     
46     /** Returns if there is any word in the trie that starts with the given prefix. */
47     public boolean startsWith(String prefix) {
48         TrieNode node = root;
49         for(int i = 0; i < prefix.length(); i++){
50             char c = prefix.charAt(i);
51             if(node.children[c - 'a'] == null){
52                 return false;
53             }else{
54                 node = node.children[c - 'a'];
55             }
56             
57         }
58         return true;
59         
60     }
61 }

 

转载于:https://www.cnblogs.com/goPanama/p/9752264.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值