zoukankan      html  css  js  c++  java
  • 单词查找树

    import java.util.ArrayList;
    import org.junit.Test;
    
    public class TriNode{
        private static final int R=256;
        private static final ArrayList<String> keysWithPrefix=new ArrayList<String>();
        
        public static void put(Node x,String word){
            if(word.length()==0) return;
            for(int i=0;i<word.length();i++){
                char key=word.charAt(i);
                if(x.next[key]==null){
                    x.next[key]=new Node();
                }
                x=x.next[key];
            }
            x.flag=true;
        }
    public static void query(Node x,String pre){ for(int i=0;i<pre.length();i++){ char ch=pre.charAt(i); if(x.next[ch]==null) return; x=x.next[ch]; } collect(x,pre); } private static void collect(Node x,String pre){ if(x==null) return; if(x.flag!=false){ keysWithPrefix.add(pre); } for(char c=0;c<R;c++){ collect(x.next[c],pre+c); } } static class Node{ private Node[] next=new Node[R]; private boolean flag=false; } @Test public void test(){ Node root=new Node(); String[] text={"by","sea","sell","sells","shell","shells","she","sho"}; for(int i=0;i<text.length;i++){ put(root,text[i]); } query(root,"se"); System.out.println(keysWithPrefix); } }
  • 相关阅读:
    Qt 学习之路:Canvas
    Qt 学习之路:模型-视图高级技术
    Qt 学习之路 :视图代理
    Qt 学习之路 :动态视图
    Qt 学习之路 :Repeater
    Qt 学习之路 :Qt Quick Controls
    mysql-gdb--oracle
    redis-BOOK
    2016qconbeijing
    LINUX 内核月报 taobao
  • 原文地址:https://www.cnblogs.com/wqkant/p/6867367.html
Copyright © 2011-2022 走看看