码迷,mamicode.com
首页 > 其他好文 > 详细

Implement Tries (Prefix Tree)

时间:2016-06-30 06:28:00      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Implement Tries (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/5628756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!