Trie树的简单实现
2024-09-07 08:52:57
import java.util.ArrayList;
import java.util.TreeMap; import util.FileOperation; 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;
} public int getSize() {
return size;
}
public void add(String word) { Node cur=root;
for(char c:word.toCharArray()) {
if(cur.next.get(c)==null)
cur.next.put(c, new Node());
cur=cur.next.get(c);
}
if(!cur.isWord) {
cur.isWord=true;
size++;
}
} public boolean find(String word) {
Node cur=root;
for(char c:word.toCharArray()) {
if(cur.next.get(c)==null)
return false;
cur=cur.next.get(c);
}
return cur.isWord;
} public boolean isPrefix(String word) {
Node cur=root;
for(char c:word.toCharArray()) {
if(cur.next.get(c)==null)
return false;
cur=cur.next.get(c);
}
return true;
} public boolean searchRegex(String word) {
return match(root,word,0);
}
private boolean match(Node node,String word,int index) {
if(index==word.length()) return node.isWord;
else {
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 w:node.next.keySet()) {
if(match(node.next.get(w), word, index+1)) {
return true;
}
}
return false;
}
}
}
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();
long endTime = System.nanoTime();
// ---
startTime = System.nanoTime();
Trie trie = new Trie();
for(String word: words)
trie.add(word);
for(String word: words)
trie.find(word);
endTime = System.nanoTime(); double time = (endTime - startTime) / 1000000000.0; System.out.println("Total different words: " + trie.getSize());
System.out.println("Trie: " + time + " s");
} }
}
最新文章
- NginxWeb服务器安装
- 【原创】Kakfa serializer包源代码分析
- SVN+Apache域用户认证配置方法_Windows(转,重新排版,部分内容更新优化)
- python3 字典相关函数
- 【堆栈应用一】一个数divided=几个最小质因数的乘积(时间复杂度On)
- 理解Null,Undefined,NAN
- 利用NTFS交换数据流隐藏文件
- hdu 1669(二分+多重匹配)
- Robotium--takeScreenshot(截图)
- 闭包用法,延迟tab
- 解析.NET对象的跨应用程序域访问(下篇)
- linux 版本控制及rpm打包
- 1020. Tree Traversals (25) -BFS
- 用Eclipse中的git提交代码流程
- selenium处理alert弹出框
- mysql的一些指令
- 9个顶级开发IoT项目的开源物联网平台
- 配置dataimport时候 如果css样式有问题 要修改index和admin的版本号
- 移动构造函数(c++11)
- 通过BurpSuite和sqlmap配合对dvwa进行sql注入测试和用户名密码暴力破解
热门文章
- Thinkpad E40热键不能使用解决办法
- HDU 5894 hannnnah_j&rsquo;s Biological Test【组合数学】
- 从2019-nCoV趋势预测问题,联想到关于网络安全态势预测问题的讨论
- 从未来看 C#
- 【OpenCv-Python】Getting Started with Images
- Java入门教程七(数组)
- jmap的使用以及内存溢出分析
- 如何使用@import导入实现了ImportBeanDefinitionRegistrar接口的类?
- ASP.NET CORE 管道模型及中间件使用解读
- text-decoration与color属性