Rust——leetcode 677. 键值映射

这篇博客介绍了如何使用Rust中的Rc和RefCell智能指针实现一个MapSum数据结构。MapSum支持插入键值对以及根据前缀计算所有匹配路径的总和。插入操作通过遍历单词并更新内部哈希映射实现,而求和功能则通过递归遍历结构完成。
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;

// 节点定义
struct Node {
    value: i32,
    next: HashMap<char, Rc<RefCell<Node>>>,
}

impl Node {
    pub fn new() -> Self {
        return Self {
            value: 0,
            next: HashMap::new(),
        };
    }
}

struct MapSum {
    root: Rc<RefCell<Node>>,
}


/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl MapSum {
    /** Initialize your data structure here. */
    fn new() -> Self {
        return MapSum {
            root: Rc::new(RefCell::new(Node::new())),
        };
    }

    fn insert(&self, key: String, val: i32) {
        let mut tmp = self.root.clone();
        // 遍历单词
        for c in key.chars() {
            let n = tmp.borrow().next.get(&c).cloned();
            if let Some(no) = n {
                tmp = no.clone();
            } else {
                let t = Rc::new(RefCell::new(Node::new()));
                tmp.borrow_mut().next.insert(c, t.clone());
                tmp = t.clone()
            };
        }
        tmp.borrow_mut().value = val;
    }

    fn sum(&self, prefix: String) -> i32 {
        let mut tmp = self.root.clone();
        for c in prefix.chars() {
            let n = tmp.borrow().next.get(&c).cloned();
            if let Some(no) = n {
                tmp = no.clone();
            } else {
                return 0;
            };
        }

        return self.recursion_sum(tmp);
    }

    fn recursion_sum(&self, node: Rc<RefCell<Node>>) -> i32 {
        let mut res = node.borrow().value;
        for (_k, v) in node.borrow().next.iter() {
            res += self.recursion_sum(v.clone())
        }

        return res;
    }
}


结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值