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;
}
}
Rust——leetcode 677. 键值映射
最新推荐文章于 2024-07-12 21:20:02 发布