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");
} }
}

最新文章

  1. NginxWeb服务器安装
  2. 【原创】Kakfa serializer包源代码分析
  3. SVN+Apache域用户认证配置方法_Windows(转,重新排版,部分内容更新优化)
  4. python3 字典相关函数
  5. 【堆栈应用一】一个数divided=几个最小质因数的乘积(时间复杂度On)
  6. 理解Null,Undefined,NAN
  7. 利用NTFS交换数据流隐藏文件
  8. hdu 1669(二分+多重匹配)
  9. Robotium--takeScreenshot(截图)
  10. 闭包用法,延迟tab
  11. 解析.NET对象的跨应用程序域访问(下篇)
  12. linux 版本控制及rpm打包
  13. 1020. Tree Traversals (25) -BFS
  14. 用Eclipse中的git提交代码流程
  15. selenium处理alert弹出框
  16. mysql的一些指令
  17. 9个顶级开发IoT项目的开源物联网平台
  18. 配置dataimport时候 如果css样式有问题 要修改index和admin的版本号
  19. 移动构造函数(c++11)
  20. 通过BurpSuite和sqlmap配合对dvwa进行sql注入测试和用户名密码暴力破解

热门文章

  1. Thinkpad E40热键不能使用解决办法
  2. HDU 5894 hannnnah_j&rsquo;s Biological Test【组合数学】
  3. 从2019-nCoV趋势预测问题,联想到关于网络安全态势预测问题的讨论
  4. 从未来看 C#
  5. 【OpenCv-Python】Getting Started with Images
  6. Java入门教程七(数组)
  7. jmap的使用以及内存溢出分析
  8. 如何使用@import导入实现了ImportBeanDefinitionRegistrar接口的类?
  9. ASP.NET CORE 管道模型及中间件使用解读
  10. text-decoration与color属性