文章

37

粉丝

68

获赞

6

访问

6.9k

头像
前缀树
综合
发布于2024年3月11日 08:20
阅读数 198


public class Code02_TrieTree {
    
    private Node root;
    
    public Code02_TrieTree() {
        this.root = new Node();
    }
    
    private static class Node {
        public int pass;
        public int end;
        public HashMap<Integer, Node> nexts;
        
        public Node() {
            this.pass = 0;
            this.end = 0;
            this.nexts = new HashMap<>();
        }
    }
    
    public void insert(String word) {
        if (word == null || "".equals(word)) return;
        char[] chars = word.toCharArray();
        Node node = root;
        node.pass++;
        Integer path = 0;
        for (int i = 0; i < chars.length; i++) {
            // 以字符的ASCII码作为路径
            path = (int) chars[i];
            if (!node.nexts.containsKey(path))
                node.nexts.put(path, new Node());
            node = node.nexts.get(path);
            node.pass++;
        }
        node.end++;
    }
    
   ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发