字典树

作者: 不再_犹豫 | 来源:发表于2020-08-06 09:13 被阅读0次
    class Tree{
        class Node {
            public int[] ch = new int[26];
        }
        public List<Node> tree = new ArrayList<Node>();
        public void insertWord(String s){
            int len = s.length(),add = 0;
            for(int i = 0;i < len;i++){
                int x = s.charAt(i) - 'a';
                if(tree.get(add).ch[x] == 0){
                    tree.add(new Node());
                    tree.get(add).ch[x] = tree.size() - 1;
                }
                add = tree.get(add).ch[x];
            }
        }
        public boolean findWord(String s){
            int add = 0;
            for(int i = 0;i < s.length();i++){
                int x = s.charAt(i) - 'a';
                if(tree.get(add).ch[x] == 0) return false;
                add = tree.get(add).ch[x];
            }
            return true;
        }
        public Tree(){
            tree.add(new Node());
        }
    }
    

    相关文章

      网友评论

          本文标题:字典树

          本文链接:https://www.haomeiwen.com/subject/xrtzrktx.html