当前位置:网站首页>208. 实现 Trie (前缀树)
208. 实现 Trie (前缀树)
2022-07-30 10:30:00 【安吉_lh1029】
1、题目描述

2、题目实现
根据题目进行分析,这个可以使用哈希表进行记录,insert就是写入哈希表的过程,search就是查询哈希表的过程,如果哈希表中查询不到,就返回false, 哈希表中查询到,就返回true. 思路还是很清晰的。
使用【哈希表】进行记录模式,实现如下:
class Trie {
Set<String> map;
public Trie() {
map = new HashSet<String>();
}
public void insert(String word) {
map.add(word);
}
public boolean search(String word) {
return map.contains(word);
}
//boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
public boolean startsWith(String prefix) {
int preLength = prefix.length();
for(String s : map){
int i = 0;
for(; i < preLength ; i++){
if( i < s.length() &&
prefix.charAt(i) != s.charAt(i))
break;
}
if(i<= s.length()
&& i == preLength){
return true;
}
}
return false;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/备注:这种实现方法的复杂度有点高,进行编译的时候, 耗时过多。可以进行进一步的优化。

边栏推荐
- 线上靶机prompt.ml
- In 2022, the top will be accepted cca shut the list
- flowable workflow all business concepts
- 【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出
- MySQL | Subqueries
- Re17: Read the paper Challenges for Information Extraction from Dialogue in Criminal Law
- Flink_CDC construction and simple use
- Verilog之数码管译码
- Security Thought Project Summary
- OC-手动引用计数内存管理
猜你喜欢
随机推荐
第1章 Kali与靶机系统
Nacos configuration in the project of battle
Re19: Read the paper Paragraph-level Rationale Extraction through Regularization: A case study on European Court
Practical Walkthrough | Calculate Daily Average Date or Time Interval in MySQL
PyQt5 - draw text on window
wsl操作
软考 系统架构设计师 简明教程 | 系统运行与软件维护
The thread pool method opens the thread -- the difference between submit() and execute()
Adaptive Control - Simulation Experiment 1 Designing Adaptive Laws Using Lyapunov's Stability Theory
多线程保证单个线程开启事务并生效的方案
By building a sequence table - teach you to calculate time complexity and space complexity (including recursion)
(BUG record) No module named PIL
数据库事务,JDBC操作和数据类型
还在用Swagger?我推荐这款零代码侵入的接口管理神器
OC-ARC (Automatic Reference Counting) automatic reference counting
Container Technology - A Simple Understanding of Kubernetes Objects
flowable workflow all business concepts
神经网络学习笔记4——自动编码器(含稀疏,堆叠)(更新中)
Redis Desktop Manager 2022.4.2 released
The method of parameter passing









