• Hiho 1014 题目


    hiho一下第二周 Hihocoder #1014 : Trie树

     

    参考链接:http://m.blog.csdn.net/blog/u012662688/38354777

     

    Java实现:

     

    import java.io.BufferedInputStream;

    import java.util.Scanner;

     

     

    public class Main {

        public static void main(String[] args) {        

            Scanner sc = new Scanner(new BufferedInputStream(System.in));

            

            //构建字典树

            int n = sc.nextInt();        

            Trie root = new Trie();//构建一棵空树,不断的往里面放节点。

            for(int i = 0;i<n;i++){

                insert(root, sc.next());

            }

              

            

            //查找字典树

            int m = sc.nextInt();        

            for(int i = 0;i<m;i++){    

                System.out.println(find(root, sc.next()));    

            }

        }

     

        //创建字典树

        public static void insert(final Trie root, String str) {

            Trie cur = root;

            for (char ch : str.toCharArray()) {

                int idx = ch - 'a';

                if (cur.child[idx] == null) {

                    cur.child[idx] = new Trie();

                }

                cur = cur.child[idx];            

                cur.num++;

            }

        }

     

        //查找字典树

        public static int find(final Trie root, String str) {

            Trie cur = root;

            for (char ch : str.toCharArray()) {

                int idx = ch - 'a';

                if (cur.child[idx] == null) {

                    return 0;

                }

                cur = cur.child[idx];

            }

            return cur.num;

        }

    }

     

    class Trie {

        Trie[] child;    

        int num;

        public Trie() {

            child = new Trie[26];

        }

    }

  • 相关阅读:
    .csproj文件
    堆栈
    数据库操作(一)
    Math数学函数
    SSM框架下各个层的解释说明
    MyBatis DAO层传递参数到mapping.xml
    Spring MVC3在controller和视图之间传递参数的方法
    注册/登陆界面验证码的作用及代码实现
    input中name和id的区别
    <mvc:default-servlet-handler/>的作用
  • 原文地址:https://www.cnblogs.com/ustc-cui/p/4639373.html
Copyright © 2020-2023  润新知