数据结构--Trie

2021-02-08  本文已影响0人  Hayley__
Trie
Trie

代码示例

import java.util.TreeMap;
public class Trie {

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

    int getSize(){
        return size;
    }
}

添加操作

    //向Trie中添加一个字符
    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中
    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;//即使遍历到最后 也无法证明word存在 要判断isWord字段;
    }

    //查询是否在Trie中有单词以prefix为前缀
    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;
    }

相关题目

上一篇下一篇

猜你喜欢

热点阅读