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
【数据结构】Trie树(字典树/前缀树) Jave实现
最新推荐文章于 2024-08-09 20:13:32 发布