前缀树问题

前缀树

思路来源

一周刷爆LeetCode,算法大神左神(左程云)耗时100天打造算法与数据结构基础到

笔记内容

  • 问题来源:力扣208.实现Trie (前缀树)

  • 问题描述:

    Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

    请你实现 Trie 类:

    • Trie() 初始化前缀树对象。
    • void insert(String word) 向前缀树中插入字符串 word
    • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
  • 算法思路

    • 记录一个空头结点
    • 插入字符串:从头结点出发查找next数组中是否含有到下一字符的路径,不存在则创建;跳到该结点,pass++;在最后一个字符对应结点时,end++;
    • 查找字符串:跟插入做法相似,查找路径,若出现next数组对应结点为空直接返回false;若到达最后一个字符,查看该点end是否大于0,若为0返回false,若大于0返回true;
    • 删除字符串:先用查找方法判断是否插入过该字符串;若存在,则按照查找的方式遍历路径,对pass--;对于最后一个字符,end--;若不存在直接返回false。
  • 代码实现

    class PrefixNode {
            public int pass;
            public int end;
            public PrefixNode[] next;
    
            public PrefixNode() {
                this.pass = 0;
                this.end = 0;
                next = new PrefixNode[26];
            }
        }
    
            //增
            public void addNode(String string){
                PrefixNode temp = head;
                char[] chars = string.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    int index = chars[i] - 'a';
                    PrefixNode node;
                    if(temp.next[index] == null){
                        node = new PrefixNode();
                    }else {
                        node = temp.next[index];
                    }
                    if(i == chars.length-1){
                        node.end++;
                    }
                    node.pass++;
                    temp.next[index] = node;
                    temp = node;
                }
    
            }
    
            //查
            public boolean search(String string){
                char[] chars = string.toCharArray();
                PrefixNode temp = head;
                for (int i = 0; i < chars.length; i++) {
                    int index = chars[i]-'a';
                    if(temp.next[index] == null){return false;}
                    temp = temp.next[index];
                }
                if(temp.end > 0){return true;}
                return false;
            }
    
            //删
            public boolean delete(String string){
                if(!search(string)){
                    return false;
                }else {
                    char[] chars = string.toCharArray();
                    PrefixNode temp = head;
                    for (int i = 0; i < chars.length; i++) {
                        int index = chars[i]-'a';
                        temp.pass--;
                        temp = temp.next[index];
                    }
                    temp.end--;
                    return true;
                }
            }
    
posted @ 2024-03-20 10:54  Noule  阅读(3)  评论(0编辑  收藏  举报