LeetCode- Implement Trie (Prefix Tree)

本文介绍了一种使用Trie树的数据结构实现,包括插入、搜索及前缀匹配等基本操作。通过对Trie节点的设计,实现了高效的字符串查找算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

Solution:

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

 

转载于:https://www.cnblogs.com/lishiblog/p/5794310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值