题解 | 字典树的实现

字典树的实现

https://www.nowcoder.com/practice/a55a584bc0ca4a83a272680174be113b

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param operators string字符串二维数组 the ops
     * @return string字符串一维数组
     */
    public String[] trieU (String[][] operators) {
        List<String> res = new ArrayList<>();
        for(String[] op: operators) {
            String type = op[0];
            String word = op[1];
            if(type.equals("1")) {
                insert(word);
            } else if(type.equals("2")) {
                delete(word);
            } else if(type.equals("3")) {
                res.add(search(word) ? "YES" : "NO");
            } else if(type.equals("4")) {
                res.add(String.valueOf(prefixNUmber(word)));
            }
        }
        return res.toArray(new String[0]);
    }



    class TrieNode {
        public int pass;
        public int end;
        public TrieNode[] nexts;

        public TrieNode() {
            pass = 0;
            end = 0;
            nexts = new TrieNode[26];
        }
    }

    private TrieNode root;

    public Solution() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = root;
        node.pass++;
        for (int i = 0; i < word.length(); i++) {
            int path = word.charAt(i) - 'a';
            if (node.nexts[path] == null) {
                node.nexts[path] = new TrieNode();
            }
            node = node.nexts[path];
            node.pass++;
        }
        node.end++;
    }

    public boolean search(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            int path = word.charAt(i) - 'a';
            if (node.nexts[path] == null) {
                return false;
            }
            node = node.nexts[path];
        }
        if (node.end > 0) {
            return true;
        }
        return false;

    }

    public void delete (String word) {
        if (search(word) == false) {
            return;
        }
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            int path = word.charAt(i) - 'a';
            node.pass--;
            node = node.nexts[path];
        }
        node.end--;
    }

    public int prefixNUmber(String pre) {
        TrieNode node = root;
        int num = 0;
        for (int i = 0; i < pre.length(); i++) {
            int path = pre.charAt(i) - 'a';
            if (node.nexts[path] == null) {
                return 0;
            }
            node = node.nexts[path];
        }
        num = node.pass;
        return num;
    }
}

全部评论

相关推荐

程序员小白条:可以,技术栈别写太多,因为学院本这块,没必要太多,项目的话可以提前,技术栈放最下面,要么技术栈放最前面,多准备下八股文
点赞 评论 收藏
分享
04-08 23:37
已编辑
东华大学 结构工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务