Trie树的插入,查前缀,查单词,删前缀和删单词。

这个Trie原先用C++就敲得很熟了,看了蓝桥杯的视频后学会把一个功能这样封装起来,以后用的时候就很爽可以直接调用了,所以就用Java写了;

public class Trie {
    private final int SIZE = 26;
    private final int HEAD = 'a';
    private int cnt;
    private int tail;
    private Trie[] next = new Trie[SIZE];
    void insert(String s) {
        Trie now = this;
        for (int i = 0; i < s.length(); i++) {
            int id = s.charAt(i) - HEAD;
            if (now.next[id] == null) {
                now.next[id] = new Trie();
            }
            now = now.next[id];
            now.cnt++;
        }
        now.tail++;
    }
    int queryPrefix(String s) {
        Trie now = this;
        for (int i = 0; i < s.length(); i++) {
            int id = s.charAt(i) - HEAD;
            if (now.next[id] == null) {
                return 0;
            }
            now = now.next[id];
        }
        return now.cnt;
    }
    int queryWord(String s) {
        Trie now = this;
        for (int i = 0; i < s.length(); i++) {
            int id = s.charAt(i) - HEAD;
            if (now.next[id] == null) {
                return 0;
            }
            now = now.next[id];
        }
        return now.tail;
    }
    void deletePrefix(String s) {
        int sum = queryPrefix(s);
        if (sum == 0) {
            return;
        }
        Trie now = this;
        for (int i = 0; i < s.length(); i++) {
            int id = s.charAt(i) - HEAD;
            now.next[id].cnt -= sum;
            if (now.next[id].cnt == 0) {
                now.next[id] = null;
                return;
            }
        }
    }
    void deleteWord(String s) {
        int sum = queryWord(s);
        if (sum == 0) {
            return;
        }
        Trie now = this;
        for (int i = 0; i < s.length(); i++) {
            int id = s.charAt(i) - HEAD;
            now.next[id].cnt -= sum;
            if (now.next[id].cnt == 0) {
                now.next[id] = null;
                return;
            }
        }
        now.tail -= sum;
    }
}
posted @ 2019-01-09 13:01  Jathon-cnblogs  阅读(301)  评论(0编辑  收藏  举报