手写trie

2019-04-23  本文已影响0人  xin激流勇进
package structures;

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;
    }

    public int getSize() {
        return size;
    }

    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(false));
            }
            cur = cur.next.get(c);
        }
        //表示不存在这个单词
        if (!cur.isWord) {
            cur.isWord = true;
            size ++;
        }
    }

    public void addRecur(String word) {
        addRecur(root, word, 0);
    }

    private void addRecur(Node node, String word, int index) {

        if (word.length() == index) {
            if (!node.isWord) {
                node.isWord = true;
                size ++;
            }
            return;
        }

        char c = word.charAt(index);
        if (node.next.get(c) == null) {
            node.next.put(c, new Node());
        }

        addRecur(node.next.get(c), word, index + 1);
    }

    public boolean containsRecur(String word) {
        return containsRecur(root, word, 0);
    }

    private boolean containsRecur(Node node, String word, int index) {
        if (word.length() == index) {
            return node.isWord;
        }

        char c = word.charAt(index);
        if (node.next.get(c) == null) {
            return false;
        }

        return containsRecur(node.next.get(c), word, index + 1);
    }

    public boolean contains(String word) {
//        Node cur = prefix(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);
        }
//
//        pan pandas 表示并查集中存在该元素
//        if (cur.isWord) {
//            return true;
//        }

//        return false;
        return cur.isWord;
    }


    private 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;
    }
}

上一篇下一篇

猜你喜欢

热点阅读