Java Trie字典树,前缀树-程序员宅基地

技术标签: java  

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

时间复杂度为O(W)

w为查询单词的长度

 

import java.util.TreeMap;

public class Trie {
	private class Node {
		public boolean isWord;
		public TreeMap<Character, Node> next;

		public Node(boolean isWord) {
			this.isWord = isWord;
			next = new TreeMap<>();
		}

		public Node() {
			this(false);
		}
	}

	private Node root;
	private int size;

	public Trie() {
		root = new Node();
		size = 0;
	}

	// 返回Trie中存储的单词数量
	public int getSize() {
		return size;
	}

	// 向Trie中添加一个新的单词word
	public void add(String word) {
		Node cur = root;
		for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if (cur.next.get(c) == null)
				cur.next.put(c, new Node());
			cur = cur.next.get(c);
		}
		if (!cur.isWord) {
			cur.isWord = true;
			size++;
		}
	}
    
	//查询单词word是否在Trie中
	public boolean contains(String word){
		Node cur=root;
		for (int i = 0; i < word.length(); i++) {
			char c=word.charAt(i);
			if(cur.next.get(c)==null)
				return false;
			cur=cur.next.get(c);
		}
		return cur.isWord;
	}
//查询是否在Trie中有单词以prefix为前缀
	public boolean isPrefix(String prefix) {
		Node cur=root;
		for (int i = 0; i < prefix.length(); i++) {
			char c=prefix.charAt(i);
			if(cur.next.get(c)==null)
				return false;
			cur=cur.next.get(c);
		}
		return true;
	}
}

测试:

public class Main {
	public static void Main(String[] args){
		 System.out.println("Pride and Prejudice");
         ArrayList<String> words=new ArrayList<>();
         if(FileOperation.readFile("pride-and-prejudice.txt", words)){

             long startTime = System.nanoTime();
             BSTSet<String> set=new BSTSet<String>();
             for(String word:words)
            	 set.add(word);
             for(String word:words)
            	 set.contains(word);

             long endTime = System.nanoTime();
             double time = (endTime - startTime) / 1000000000.0;

             System.out.println("Total different words: " + set.getSize());
             System.out.println("BSTSet: " + time + " s");
             
             startTime = System.nanoTime();

             Trie trie = new Trie();
             for(String word: words)
                 trie.add(word);

             for(String word: words)
                 trie.contains(word);

             endTime = System.nanoTime();

             time = (endTime - startTime) / 1000000000.0;

             System.out.println("Total different words: " + trie.getSize());
             System.out.println("Trie: " + time + " s");
         }
	}
}

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

import java.util.TreeMap;

public class WordDictionary {
	public class Node{
	private boolean isWord;
	public TreeMap<Character, Node> next;
	public Node(boolean isWord){
		this.isWord=isWord;
		next=new TreeMap<>();
	}
		public Node() {
			this(false);
		}
	}
	 private  Node root; 
	 
     public WordDictionary(){
    	 root =new Node();
     }

	public void addWord(String word) {
		Node cur = root;
		for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if (cur.next.get(c) == null)
				cur.next.put(c, new Node());
			cur = cur.next.get(c);
		}
		cur.isWord = true;
	}
     public boolean search(String word){
    	 return match(root, word, 0);
     }
     private boolean match(Node node,String word,int index) {
		if(index==word.length()) 
			return node.isWord;
		char c=word.charAt(index);
		if(c!='.'){
			if(node.next.get(c)==null)
				return false;
			return match(node.next.get(c), word, index+1);
		}else{
			for (char nextChar :node.next.keySet()) {
				if(match(node.next.get(nextChar), word, index+1))
					return true;
			}
			return false;	
		}
	}
}

  Trie和映射

import java.util.TreeMap;

public class MapSum {
	private class Node{
		public boolean isWord;
		public int value;
		
		public TreeMap<Character, Node> next;
		public Node(int value){
			this.value=value;
			next=new TreeMap<>();
		}
		public Node(){this(0);}
	}
	private Node root;
	public MapSum() {
		root=new Node();
	}
	public void insert(String word,int val){
		Node cur=root;
		for (int i = 0; i < word.length(); i++) {
			char c=word.charAt(i);
			if(cur.next.get(c)==null)
				cur.next.put(c,new Node());
			cur=cur.next.get(c);
		}
     cur.value=val;
	}
	public int sum(String prefix){
		Node cur=root;
		for (int i = 0; i < prefix.length(); i++) {
			char c=prefix.charAt(i);
			if(cur.next.get(c)==null)
				return 0;
			cur=cur.next.get(c);
		}
	    return sum(cur);	
	}
	private int sum(Node node){
		if(node.next.size()==0)
			return node.value;
		int res=node.value;
		for (char c:node.next.keySet()) 
			res+=sum(node.next.get(c));
		return res;
	}
}

  

转载于:https://www.cnblogs.com/sunliyuan/p/10742774.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30415113/article/details/96692916

智能推荐

POJ-1861,Network,最小生成树水题,,注意题面输出有问题,不必理会~~_andrew is working as system administrator and is p-程序员宅基地

文章浏览阅读1.6k次。NetworkTime Limit: 1000MS Memory Limit: 30000K Special Judgehttp://poj.org/problem?id=1861DescriptionAndrew is working as system administrator and _andrew is working as system administrator and is planning to estab pojlish a

[coc.nvim] clangd was not found on your PATH. :CocCommand clangd.install will install 12.0.1._the clangd language server is not installed.-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏4次。报错:[coc.nvim] clangd was not found on your PATH. :CocCommand clangd.install will install 12.0.1.解决方案打开vim执行如下命令CocInstall coc-clangd执行结果如下图所示:如果执行失败,可以点击此处手动下载,解压后放至如下目录# linux$HOME/.config/coc/extensions/coc-clangd-data/install/12.0.1# wind._the clangd language server is not installed.

gcc,g++_g++ -iquote-程序员宅基地

文章浏览阅读2.5k次。http://www.360doc.com/content/12/0211/08/6828497_185707599.shtml gcc [-c|-S|-E] [-std=standard] [-g] [-pg] [-Olevel] [-Wwarn...] [-pedantic] [-Idir...]_g++ -iquote

牛客网Leetcode刷题模板 C++ 笔记_牛客刷题数据结构c++-程序员宅基地

文章浏览阅读542次。牛客网Leetcode刷题模板 C++ 笔记1.模板&常见操作2.数据结构1.栈2.队列1.模板&常见操作#include <bits/stdc++.h>using namespace std;int main(){ int n; cin>>n; while(n--){ xxxx return 0;}2.数据结构1.栈stack<int> L;L.empty() 堆栈为空_牛客刷题数据结构c++

STM32控制矩阵按键,HAL库,cubeMX配置_stm32 (基于hal库)4×4矩阵按键 cubemax-程序员宅基地

文章浏览阅读2.1k次,点赞4次,收藏31次。stm32,hal库,cubeMX配置。行列扫描:和逐行或逐列扫描不通的是行列扫描;扫描原理是先把高4位设置为低电平,把低4位设置为高电平,这样如果低4位中有电平变低,说明该列有按键按下,但不知道具体是哪一行的按键;接着反过来操作,把高4位设置为高电平,低四位设置为低电平,检测高4位哪一位被拉低,那么按键就在对应的行上,这样通过两次扫描就知道该按键在哪一行哪一列了, 也就知道具体是哪个按键被按下了。..._stm32 (基于hal库)4×4矩阵按键 cubemax

JSP一些知识点_<%=get int()%>-程序员宅基地

文章浏览阅读1.4k次,点赞3次,收藏3次。<%%> 与 <%!%> 和 <%=%>的区别名称作用<%%>脚本片段其内容会翻译在Servlet的Service方法中;可以定义局部变量或者调用方法,但不能定义方法<%!%>声明其内容会直接翻译在Servlet类中,可以定义方法、属性、全局变量<%=%>JSP表达式将已经声明的变量或者表达式输出到页面参考资料:https://www.cnblogs.com/mark5/p/1159_

随便推点

Oracle 用户授权、权限收回、角色创建 编辑 删除_oracle 有条件收回查询权限-程序员宅基地

文章浏览阅读1.7k次。用户授权--查询数据库中的所有用户select * from dba_users; --锁住用户alter user username account lock;--给用户解锁alter user username account unlock; --创建用户create user username identified by password;--授权用户创建表grant..._oracle 有条件收回查询权限

RGB YUV转换原理_c# rgb转yv12-程序员宅基地

文章浏览阅读1.5k次。[+]RGB TO YUV转换原理及代码示例数据表述方式转换公式代码示例1前言2YUV相关色彩空间模型1YUV 与 YIQ YcrCb3YUV2RGB快速算法分析1整型算法2部分查表法3完全查表法4进一步的思考4RGB2YUV RGB TO YUV转换原理及代码示例[转]RGB TO YUV转换原理及代码示例 _c# rgb转yv12

Python基础篇--学习记录2.0-程序员宅基地

文章浏览阅读988次,点赞23次,收藏11次。hash是一类算法,算法就是功能.我们可以看为一个函数.给它传入一段内容,它经过运算之后,就会返回一串hash值或者说是散列值,而它就是一串字符串常见的hash算法有md5,sha1,sha256,sha512等等,它们的功能都是一样的,只是算法的负责程度是不一样的。

python对医疗数据进行分析,看看男女生病几率_python医疗数据分析-程序员宅基地

文章浏览阅读947次,点赞2次,收藏19次。嗨喽,大家好呀~这里是爱看美女的茜茜呐明确目的–获得数据(爬虫,现有,公开的数据)–数据预处理——数据可视化——结论。_python医疗数据分析

键盘符号输入 Alt+小键盘数字(希腊字母)_alt键码输入希腊字符-程序员宅基地

文章浏览阅读208次。24个希腊字母表_alt键码输入希腊字符

java环境的配置——实现win10下双击直接运行jar文件-程序员宅基地

文章浏览阅读5.6k次,点赞3次,收藏5次。在渗透测试的过程中很多工具的安装和使用需要java环境,下面我来介绍一下java环境配置的超详细步骤(包含怎样实现win10下双击直接运行jar文件)_java环境的配置——实现win10下双击直接运行jar文件

推荐文章

热门文章

相关标签