当前位置:网站首页>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);
*/
备注:这种实现方法的复杂度有点高,进行编译的时候, 耗时过多。可以进行进一步的优化。
边栏推荐
- ospf2 two-point two-way republish (question 2)
- Beyond Stream Processing !第四届实时计算 Flink 挑战赛启动,49 万奖金等你来拿!
- MFCC转音频,效果不要太逗>V<!
- [100 Solidity Skills] 1. Contract reentrancy attack
- Js array operating mobile for encapsulation
- Understanding of deadlock
- 安全提示:Qt中的FreeType
- Classes and Objects - 6 Default Member Functions
- Re20:读论文的先例:普通法的信息理论分析
- Linux内核设计与实现(十)| 页高速缓存和页回写
猜你喜欢
PyQt5 - draw text on window
Verilog之数码管译码
张量篇-初步
梅科尔工作室-看鸿蒙设备开发实战笔记四——内核开发
[Qualcomm][Network] 网络拨号失败和netmgrd服务分析
Domino Server SSL Certificate Installation Guide
Beyond Stream Processing !第四届实时计算 Flink 挑战赛启动,49 万奖金等你来拿!
Flask's routing (app.route) detailed
360发布面向未来的EDR,全方位守护政企用户终端安全
Re17: Read the paper Challenges for Information Extraction from Dialogue in Criminal Law
随机推荐
Re15: Read the paper LEVEN: A Large-Scale Chinese Legal Event Detection Dataset
Log4j有哪几种日志级别呢?
Linux内核设计与实现(十)| 页高速缓存和页回写
PyQt5 - draw text on window
死锁的理解
JCL learning
MFCC转音频,效果不要太逗>V<!
Re19: Read the paper Paragraph-level Rationale Extraction through Regularization: A case study on European Court
flowable workflow all business concepts
(***Key points***) Flink common memory problems and tuning guide (1)
Basemap and Seaborn
The thread pool method opens the thread -- the difference between submit() and execute()
spark udf accepts and handles null values.
OC- about alloc and dealloc (haven't started writing yet)
Scrapy爬虫之网站图片爬取
Flask's routing (app.route) detailed
神经网络学习笔记3——LSTM长短期记忆网络
MySQL之数据库维护
在机器人行业的专业人士眼里,机器人行业目前的情况如何?
Security Thought Project Summary