Trie树的java实现

package com.liyiwen.TestTrie;

/**
 * Created by dell on 2015/7/12.
 */
public class Trie {
    private int size = 26;
    private TrieNode root;
    private  class TrieNode{
        private int passCount;
        private boolean isEnd;
        private TrieNode[] nodes;
        private char val;

        public TrieNode(){
            passCount = 1;
            isEnd = false;
            nodes = new TrieNode[size];
        }
    }

    public static Trie getInstance(){
        return new Trie();
    }

    private Trie(){
        root = new TrieNode();
    }
    public void insert(String str){
        if (null == str || str.isEmpty()){
            return;
        }
        TrieNode node = root;
        char[] charArray = str.toCharArray();
        for (char val : charArray){
            int index = val - 'a';
            if (null == node.nodes[index]){
                node.nodes[index] = new TrieNode();
                node.nodes[index].val = val;
            }else{
                node.nodes[index].passCount++;
            }

            node = node.nodes[index];
        }

        node.isEnd = true;
    }

    public boolean hasString(String extStr){
        if (null == extStr || extStr.isEmpty())
            return false;
        char[] chars = extStr.toCharArray();
        TrieNode node = root;
        for (char val : chars) {
            int index = val - 'a';
            if (null == node.nodes[index]) {
                return false;
            } else {
                node = node.nodes[index];
            }
        }

        return node.isEnd;
    }

    public int preCount(String pex){
        if (null == pex || pex.isEmpty())
            return 0;
        TrieNode node = root;
        char[] chars = pex.toCharArray();

        for (char val : chars){
            int index = val - 'a';
            if (null == node.nodes[index]){
                return 0;
            }else {
                node = node.nodes[index];
            }
        }

        return node.passCount;
    }

    private void preOrderTraverse(TrieNode node){
        if (node != null) {
            System.out.print(node.val + "-");

            for (TrieNode sonNode : node.nodes) {
                preOrderTraverse(sonNode);
            }
        }
    }

    private TrieNode getRoot(){
        return root;
    }

    public void preOrderTraverse(){
        preOrderTraverse(getRoot());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值