Trie查询每个条目的时间复杂度,和字典中一共有多少条无关。

时间复杂度为O(W)

w为查询单词的长度

  1. import java.util.TreeMap;
  2.  
  3. public class Trie {
  4. private class Node {
  5. public boolean isWord;
  6. public TreeMap<Character, Node> next;
  7.  
  8. public Node(boolean isWord) {
  9. this.isWord = isWord;
  10. next = new TreeMap<>();
  11. }
  12.  
  13. public Node() {
  14. this(false);
  15. }
  16. }
  17.  
  18. private Node root;
  19. private int size;
  20.  
  21. public Trie() {
  22. root = new Node();
  23. size = 0;
  24. }
  25.  
  26. // 返回Trie中存储的单词数量
  27. public int getSize() {
  28. return size;
  29. }
  30.  
  31. // 向Trie中添加一个新的单词word
  32. public void add(String word) {
  33. Node cur = root;
  34. for (int i = 0; i < word.length(); i++) {
  35. char c = word.charAt(i);
  36. if (cur.next.get(c) == null)
  37. cur.next.put(c, new Node());
  38. cur = cur.next.get(c);
  39. }
  40. if (!cur.isWord) {
  41. cur.isWord = true;
  42. size++;
  43. }
  44. }
  45.  
  46. //查询单词word是否在Trie中
  47. public boolean contains(String word){
  48. Node cur=root;
  49. for (int i = 0; i < word.length(); i++) {
  50. char c=word.charAt(i);
  51. if(cur.next.get(c)==null)
  52. return false;
  53. cur=cur.next.get(c);
  54. }
  55. return cur.isWord;
  56. }
  1. //查询是否在Trie中有单词以prefix为前缀
  2. public boolean isPrefix(String prefix) {
  3. Node cur=root;
  4. for (int i = 0; i < prefix.length(); i++) {
  5. char c=prefix.charAt(i);
  6. if(cur.next.get(c)==null)
  7. return false;
  8. cur=cur.next.get(c);
  9. }
  10. return true;
  11. }
  12. }

测试:

  1. public class Main {
  2. public static void Main(String[] args){
  3. System.out.println("Pride and Prejudice");
  4. ArrayList<String> words=new ArrayList<>();
  5. if(FileOperation.readFile("pride-and-prejudice.txt", words)){
  6.  
  7. long startTime = System.nanoTime();
  8. BSTSet<String> set=new BSTSet<String>();
  9. for(String word:words)
  10. set.add(word);
  11. for(String word:words)
  12. set.contains(word);
  13.  
  14. long endTime = System.nanoTime();
  15. double time = (endTime - startTime) / 1000000000.0;
  16.  
  17. System.out.println("Total different words: " + set.getSize());
  18. System.out.println("BSTSet: " + time + " s");
  19.  
  20. startTime = System.nanoTime();
  21.  
  22. Trie trie = new Trie();
  23. for(String word: words)
  24. trie.add(word);
  25.  
  26. for(String word: words)
  27. trie.contains(word);
  28.  
  29. endTime = System.nanoTime();
  30.  
  31. time = (endTime - startTime) / 1000000000.0;
  32.  
  33. System.out.println("Total different words: " + trie.getSize());
  34. System.out.println("Trie: " + time + " s");
  35. }
  36. }
  37. }

  search可以搜索文字或正则表达式字符串,字符串只包含字母.或者a-z.

  1. import java.util.TreeMap;
  2.  
  3. public class WordDictionary {
  4. public class Node{
  5. private boolean isWord;
  6. public TreeMap<Character, Node> next;
  7. public Node(boolean isWord){
  8. this.isWord=isWord;
  9. next=new TreeMap<>();
  10. }
  11. public Node() {
  12. this(false);
  13. }
  14. }
  15. private Node root;
  16.  
  17. public WordDictionary(){
  18. root =new Node();
  19. }
  20.  
  21. public void addWord(String word) {
  22. Node cur = root;
  23. for (int i = 0; i < word.length(); i++) {
  24. char c = word.charAt(i);
  25. if (cur.next.get(c) == null)
  26. cur.next.put(c, new Node());
  27. cur = cur.next.get(c);
  28. }
  29. cur.isWord = true;
  30. }
  31. public boolean search(String word){
  32. return match(root, word, 0);
  33. }
  34. private boolean match(Node node,String word,int index) {
  35. if(index==word.length())
  36. return node.isWord;
  37. char c=word.charAt(index);
  38. if(c!='.'){
  39. if(node.next.get(c)==null)
  40. return false;
  41. return match(node.next.get(c), word, index+1);
  42. }else{
  43. for (char nextChar :node.next.keySet()) {
  44. if(match(node.next.get(nextChar), word, index+1))
  45. return true;
  46. }
  47. return false;
  48. }
  49. }
  50. }

  Trie和映射

  1. import java.util.TreeMap;
  2.  
  3. public class MapSum {
  4. private class Node{
  5. public boolean isWord;
  6. public int value;
  7.  
  8. public TreeMap<Character, Node> next;
  9. public Node(int value){
  10. this.value=value;
  11. next=new TreeMap<>();
  12. }
  13. public Node(){this(0);}
  14. }
  15. private Node root;
  16. public MapSum() {
  17. root=new Node();
  18. }
  19. public void insert(String word,int val){
  20. Node cur=root;
  21. for (int i = 0; i < word.length(); i++) {
  22. char c=word.charAt(i);
  23. if(cur.next.get(c)==null)
  24. cur.next.put(c,new Node());
  25. cur=cur.next.get(c);
  26. }
  27. cur.value=val;
  28. }
  29. public int sum(String prefix){
  30. Node cur=root;
  31. for (int i = 0; i < prefix.length(); i++) {
  32. char c=prefix.charAt(i);
  33. if(cur.next.get(c)==null)
  34. return 0;
  35. cur=cur.next.get(c);
  36. }
  37. return sum(cur);
  38. }
  39. private int sum(Node node){
  40. if(node.next.size()==0)
  41. return node.value;
  42. int res=node.value;
  43. for (char c:node.next.keySet())
  44. res+=sum(node.next.get(c));
  45. return res;
  46. }
  47. }

  

Java Trie字典树,前缀树的更多相关文章

  1. 9-11-Trie树/字典树/前缀树-查找-第9章-《数据结构》课本源码-严蔚敏吴伟民版

    课本源码部分 第9章  查找 - Trie树/字典树/前缀树(键树) ——<数据结构>-严蔚敏.吴伟民版        源码使用说明  链接☛☛☛ <数据结构-C语言版>(严蔚 ...

  2. [LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  3. [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...

  4. 内存空间有限情况下的词频统计 Trie树 前缀树

    数据结构与算法专题--第十二题 Trie树 https://mp.weixin.qq.com/s/nndr2AcECuUatXrxd3MgCg

  5. Trie - leetcode [字典树/前缀树]

    208. Implement Trie (Prefix Tree) 字母的字典树每个节点要定义一个大小为26的子节点指针数组,然后用一个标志符用来记录到当前位置为止是否为一个词,初始化的时候讲26个子 ...

  6. LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))

    Implement a trie with insert, search, and startsWith methods. 实现字典树,前面好像有道题做过类似的东西,代码如下: class TrieN ...

  7. HDU 1251 字典树(前缀树)

    题目大意 :Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).(单词互不相同) ...

  8. Trie(前缀树/字典树)及其应用

    Trie,又经常叫前缀树,字典树等等.它有很多变种,如后缀树,Radix Tree/Trie,PATRICIA tree,以及bitwise版本的crit-bit tree.当然很多名字的意义其实有交 ...

  9. TRIE 字典树 前缀紧急集合!

    TRIE: 在计算机科学中,Trie,又称前缀树或字典树,是一种有序树状的数据结构,用于保存关联数组,其中的键通常是字符串.——百度百科 自我理解: trie树,是一种处理字符串前缀的数据结构,通常会 ...

随机推荐

  1. P3709 大爷的字符串题 (莫队)

    题目 P3709 大爷的字符串题 题意:求\([l,r]\)中众数的个数. 解析 维护两个数组: \(cnt[x]\),数\(x\)出现的次数. \(sum[x]\),出现次数为\(x\)的数的个数. ...

  2. 【CF1152F】Neko Rules the Catniverse(动态规划)

    [CF1152F]Neko Rules the Catniverse(动态规划) 题面 CF 题解 我们先考虑一个需要扫一遍所有位置的做法. 那么状态一定是\(f[i]\)然后什么什么表示考虑到当前第 ...

  3. cinder-volume报错vmdk2 is reporting problems, not sending heartbeat. Service will appear "down".

    cinder-volume报错vmdk2 is reporting problems, not sending heartbeat. Service will appear "down&qu ...

  4. [HNOI/AHOI2018]毒瘤

    题目描述 https://www.lydsy.com/JudgeOnline/upload/201804/%E6%B9%96%E5%8D%97%E4%B8%80%E8%AF%95%E8%AF%95%E ...

  5. 【优秀的图片后期编辑工具】Luminar 3.1 for Mac

     [简介] 今天和大家分享最新的 Luminar for Mac 3.1 版本,支持中文界面,Luminar是一款Mac上优秀的图片后期处理工具,功能类似 Photoshop Lightroom 等软 ...

  6. font-family

    Font-family: Helvetica, Tahoma, Arial, “Microsoft YaHei”, “微软雅黑”, SimSun, “宋体”, STXihei, “华文细黑”, Hei ...

  7. H5_0002:微信分享设置

    1,非公众号的链接,设置分享的预览图片. 先打开页面,在收藏页面,最后在收藏界面长按 “转发” ,即可在链接上出现预览图片.

  8. table自适应大小,以及内容换行

    在table的样式中加入以下两个样式: table-layout: fixed; word-wrap:break-word;

  9. addEventListener解决多个window.onscroll共存的2个方法

    方法1.(注意第一个和第二个的先后次序) window.onscroll=function(){console.log('第一个');} var oldMethod = window.onscroll ...

  10. git体验

    (1)git初始化配置#配置用户名git config --global user.name "azcode"#配置邮箱git config --global user.email ...