zoukankan      html  css  js  c++  java
  • Java字典树

    研一的时候软件工程课上老师让实现一个计算文本中某字符串的频率,第一想法就是hashmap键值对,然后老师将给定的1M文本换成了100M,1G。。我还记得第一节课100M测试文档我用笔记本跑了十分钟。。后来师兄提醒用字典树,然后靠着度娘“实现”了老师的要求。。今天心血来潮,又把字典树捡起来简单写了一遍
    package Trie;
    /**
     * 字典树
     * */
    public class DicTree {
        public static Node root;
    
        static class Node {
            char c;
            int num;
            Node[] son;
    
            public Node() {
                this.son = new Node[26];
            }
        }
    
        public DicTree() {
            this.root = new Node();
        }
    
        public static void insert(String str) {
            if (str == null || str.length() == 0)
                return;
            char[] chars = str.toCharArray();
            int pos;
            Node now = root;
            for (int i = 0, length = chars.length; i < length; i++) {
                Node newNode = new Node();
                pos = chars[i] - 'a';
                if (now.son[pos] == null) {
                    now.son[pos].num++;
    
                } else {
                    now.son[pos].num = 1;
                }
                now = now.son[pos];
            }
        }
    
        //求某字符串的数量
        public static int count(String str) {
            char[] chars = str.toCharArray();
            Node now = root;
            for (int i = 0; i < str.length(); i++) {
                int pos = chars[i] - 'a';
                now = now.son[pos];
            }
            return now.num;
        }
    
    }
     
  • 相关阅读:
    Python()- 面向对象的组合用法
    HASHMAP 深入解析
    java深入解析
    centos 防火墙关闭/开启
    idea讲web项目部署到tomcat,热部署
    idea真不习惯啊
    JetbrainsCrack
    js 模块化
    JavaWeb中session创建与销毁的问题
    前端导出文件功能document.execCommand命令
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400692.html
Copyright © 2011-2022 走看看