【数据结构】Trie树(字典树/前缀树) Jave实现

import com.fayetech.commons.util.JsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.TreeMap;

/**
 * @author zhujianjian
 * @date 2023/1/3 14:55
 * @desc Trie树(字典树/前缀树)
 */
@Data
@Slf4j
public class Trie_Tree_Test {

    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_Tree_Test(){
        this.root = new Node();
        this.size = 0;
    }

    /**
     * 获取Trie树种存储的单词数量
     * @return
     */
    public int getSize(){
        return size;
    }

    /**
     * 向Trie树中添加一个新的单词word
     * @param word
     */
    public void add(String word){
        Node cur = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(cur.next.get(c) == null){
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        if(!cur.isWord){
            cur.isWord = true;
            size++;
        }
    }

    /**
     * 查询单词word是否在Trie树中
     * @param word
     * @return
     */
    public boolean contains(String word){
        Node cur = root;
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 查询是否在Trie树种有单词以prefix为前缀
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix){
        Node cur = root;
        for(int i = 0; i < prefix.length(); i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }

    @Test
    public void test01() {
        Trie_Tree_Test trieTree = new Trie_Tree_Test();
        trieTree.add("hello");
        trieTree.add("world");
        trieTree.add("java");
        trieTree.add("program");
        trieTree.add("art");
        System.out.println(trieTree.contains("python"));
        System.out.println(trieTree.contains("java"));
        System.out.println(trieTree.isPrefix("pro"));
//        System.out.println(JsonUtils.toJson(trieTree));
    }

}

copy code & run ->

@Test
    public void test01()

result ->

false
true
true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值