Implement Tries (Prefix Tree)

本文介绍了一种使用Trie树的数据结构实现方法,包括插入、搜索和前缀匹配等功能。通过具体的代码示例详细展示了如何创建Trie树节点,并实现字符串的操作。
 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");

 

转载于:https://www.cnblogs.com/shuashuashua/p/5628756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值