其他分享
首页 > 其他分享> > 力扣 - 677. 键值映射

力扣 - 677. 键值映射

作者:互联网

目录

题目

677. 键值映射

思路

代码

class MapSum {

    private TrieNode root;
    private int sum;

    public MapSum() {
        root = new TrieNode();
    }
    
    public void insert(String key, int val) {
        TrieNode node = root;

        for (int i = 0; i < key.length(); i++) {
            if (node.children[key.charAt(i) - 'a'] == null) {
                node.children[key.charAt(i) - 'a'] = new TrieNode();
            }
            node = node.children[key.charAt(i) - 'a'];
        }
        // 不存在的话,在前缀树的单词最后一个字符位置初始该值;若存在,就替换
        node.val = val;
    }
    
    public int sum(String prefix) {
        sum = 0;
        TrieNode node = root;

        // 查看该前缀是否存在
        for (int i = 0; i < prefix.length(); i++) {
            if (node.children[prefix.charAt(i) - 'a'] == null) {
                return sum;
            }
            node = node.children[prefix.charAt(i) - 'a'];
        }
        // 前序遍历,递归计算总和
        getSum(node);
        return sum;
    }

    /**
    * N叉树的前序遍历
    */
    private void getSum(TrieNode node) {
        if (node == null) {
            return;
        }
        sum += node.val;
        for (int i = 0; i < 26; i++) {
            getSum(node.children[i]);
        }
    }

    private class TrieNode {
        int val;
        TrieNode[] children;

        TrieNode() {
            val = 0;
            children = new TrieNode[26];
        }
    }
}

复杂度分析

标签:node,val,TrieNode,sum,677,力扣,int,键值,children
来源: https://www.cnblogs.com/linzedian/p/14131313.html