字典树
来源:互联网 发布:java语言的特点是什么 编辑:程序博客网 时间:2024/06/06 10:01
背景:
代码:
public class Problem_23_TrieTree {public static class TrieNode {public int path;public int end;public TrieNode[] map;public TrieNode() {path = 0;end = 0;map = new TrieNode[26];}}public static class Trie {private TrieNode root;public Trie() {root = new TrieNode();}public void insert(String word) {if (word == null) {return;}char[] chs = word.toCharArray();TrieNode node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.map[index] == null) {node.map[index] = new TrieNode();}node = node.map[index];node.path++;}node.end++;}public void delete(String word) {if (search(word)) {char[] chs = word.toCharArray();TrieNode node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.map[index].path-- == 1) {node.map[index] = null;return;}node = node.map[index];}node.end--;}}public boolean search(String word) {if (word == null) {return false;}char[] chs = word.toCharArray();TrieNode node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.map[index] == null) {return false;}node = node.map[index];}return node.end != 0;}public int prefixNumber(String pre) {if (pre == null) {return 0;}char[] chs = pre.toCharArray();TrieNode node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.map[index] == null) {return 0;}node = node.map[index];}return node.path;}}public static void main(String[] args) {Trie trie = new Trie();System.out.println(trie.search("zuo"));trie.insert("zuo");System.out.println(trie.search("zuo"));trie.delete("zuo");System.out.println(trie.search("zuo"));trie.insert("zuo");trie.insert("zuo");trie.delete("zuo");System.out.println(trie.search("zuo"));trie.delete("zuo");System.out.println(trie.search("zuo"));trie.insert("zuoa");trie.insert("zuoac");trie.insert("zuoab");trie.insert("zuoad");trie.delete("zuoa");System.out.println(trie.search("zuoa"));System.out.println(trie.prefixNumber("zuo"));}}
阅读全文
0 0
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树。。
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 在外围获取APP的机密信息
- Codeforces Round #438 (Div. 1 + Div. 2 combined)
- 嵌套的面板
- C#读写INI文件
- Spring事物失效问题
- 字典树
- RNN循环神经网络学习笔记
- codevs 2038 香甜的黄油 SPFA 解题报告
- jsp登录并实现邮箱激活功能
- Codeforces Round #438 C 868C Qualification Rounds(思维,非状压dp)
- Linux —— 键盘操作命令及通配符的使用
- Tomcat部署项目之通过server.xml部署项目
- 解码HTML Entity
- 第四讲,网络应用(下)