博客
关于我
【leetcode】208. 实现 Trie (前缀树)
阅读量:546 次
发布时间:2019-03-09

本文共 1978 字,大约阅读时间需要 6 分钟。

Trie(发音类似 “try”)是一种树形数据结构,常用于高效存储和检索字符串集合中的键。其主要应用场景包括自动补全和拼写检查。Trie通过分叉树的方式组织数据,使得查找和插入操作效率极高。

Trie Class 实现

class Trie {    private class Node {        private boolean isWord; // 标记是否为单词结尾        private HashMap
next; // 子节点映射 public Node(boolean isWord) { this.isWord = isWord; this.next = new HashMap<>(); } public Node() { this(false); } } private Node root; // 根节点 private int size; // 预留字段,不使用 public Trie() { this.root = new Node(); size = 0; } // 插入单词 public void insert(String word) { Node current = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!current.next.containsKey(c)) { current.next.put(c, new Node()); } current = current.next.get(c); } if (!current.isWord) { current.isWord = true; size++; } } // 检查单词存在 public boolean search(String word) { Node current = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!current.next.containsKey(c)) { return false; } current = current.next.get(c); } return current.isWord; } // 检查是否以某个前缀开头 public boolean startsWith(String prefix) { Node current = root; for (int i = 0; i < prefix.length(); i++) { char c = prefix.charAt(i); if (!current.next.containsKey(c)) { return false; } current = current.next.get(c); } return true; }}

使用示例

Trie trie = new Trie();trie.insert("apple"); // 插入单词bool result = trie.search("apple"); // 检查是否存在单词result = trie.search("app"); // 检查是否存在单词bool startsResult = trie.startsWith("app"); // 检查是否以特定前缀开头

提示

  • 单词和前缀的长度不超过2000个字符
  • insert、search 和 startsWith 调用次数总计不超过 3 × 104 次
  • 单词仅由小写字母组成
  • 提高Trie性能的重要因素是复杂度为 O(m),其中 m 是处理的字符数

转载地址:http://tmhiz.baihongyu.com/

你可能感兴趣的文章
nodejs图片转换字节保存
查看>>
NodeJs学习笔记001--npm换源
查看>>
Nodejs教程09:实现一个带接口请求的简单服务器
查看>>
Nodejs简介以及Windows上安装Nodejs
查看>>
nodejs系列之express
查看>>
nodejs配置express服务器,运行自动打开浏览器
查看>>
Node入门之创建第一个HelloNode
查看>>
Node出错导致运行崩溃的解决方案
查看>>
node安装及配置之windows版
查看>>
Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
查看>>
NOIp2005 过河
查看>>
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>