《程序员代码面试指南》第五章 字符串问题 字典树(前缀树)的实现

时间:2022-12-30 14:44:37

题目

字典树(前缀树)的实现

java代码

package com.lizhouwei.chapter5;

/**
 * @Description: 字典树(前缀树)的实现
 * @Author: lizhouwei
 * @CreateDate: 2018/4/25 21:34
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter5_23 {
    public TrieNode root;

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

    public void insert(String str) {
        char[] chars = str.toCharArray();
        TrieNode node = root;
        int index = 0;
        for (int i = 0; i < chars.length; i++) {
            index = chars[i] - 'a';
            if (node.map[index] == null) {
                node.map[index] = new TrieNode();
            }
            node = node.map[index];
            node.pathNum++;
        }
    }

    public void delete(String str) {
        if (!search(str)) {
            return;
        }
        char[] chars = str.toCharArray();
        TrieNode node = root;
        int index = 0;

        for (int i = 0; i < chars.length; i++) {
            index = chars[i] - 'a';
            node = node.map[index];
            if (node.pathNum-- == 1) {
                node.map[index] = null;
                return;
            }
        }
        node.endNum--;
    }

    public boolean search(String str) {
        char[] chars = str.toCharArray();
        TrieNode node = root;
        int index = 0;
        for (int i = 0; i < chars.length; i++) {
            index = chars[i] - 'a';
            node = node.map[index];
            if (node == null) {
                return false;
            }
        }
        return node.endNum != 0;
    }

    public int prefixNumber(String str) {
        char[] chars = str.toCharArray();
        TrieNode node = root;
        int index = 0;

        for (int i = 0; i < chars.length; i++) {
            index = chars[i] - 'a';
            node = node.map[index];
            if (node == null) {
                return 0;
            }
        }
        return node.pathNum;
    }

    //测试
    public static void main(String[] args) {
        Chapter5_23 chapter = new Chapter5_23();
        String[] strs = {"abc", "abcd", "abd", "b", "bcd", "efg", "hik"};
        for (String str : strs) {
            chapter.insert(str);
        }
        boolean exist = chapter.search("abc");
        System.out.println("abc是否在字典树中:" + exist);
        System.out.println("字典树中删除abc");
        chapter.delete("abc");
        exist = chapter.search("abc");
        System.out.println("abc是否在字典树中:" + exist);
        int result = chapter.prefixNumber("abc");
        System.out.println("以abc作为前缀的字符串的个数:" + result);
    }
}

class TrieNode {
    public int pathNum;
    public int endNum;
    public TrieNode[] map;

    public TrieNode() {
        pathNum = 0;
        endNum = 0;
        map = new TrieNode[26];
    }
}

结果

《程序员代码面试指南》第五章 字符串问题 字典树(前缀树)的实现