diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 3d986a82..69713c62 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -493,6 +493,33 @@ object Solution { } ``` +rust: + +```rust +impl Solution { + pub fn is_valid(s: String) -> bool { + if s.len() % 2 == 1 { + return false; + } + let mut stack = vec![]; + let mut chars: Vec = s.chars().collect(); + while let Some(s) = chars.pop() { + match s { + ')' => stack.push('('), + ']' => stack.push('['), + '}' => stack.push('{'), + _ => { + if stack.is_empty() || stack.pop().unwrap() != s { + return false; + } + } + } + } + stack.is_empty() + } +} +``` +

diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index bf90b89b..78dfae3e 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -420,6 +420,41 @@ object Solution { } ``` + +rust: + +```rust +impl Solution { + pub fn eval_rpn(tokens: Vec) -> i32 { + let mut stack = vec![]; + for token in tokens.into_iter() { + match token.as_str() { + "+" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() += a; + } + "-" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() -= a; + } + "*" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() *= a; + } + "/" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() /= a; + } + _ => { + stack.push(token.parse::().unwrap()); + } + } + } + stack.pop().unwrap() + } +} +``` +

diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 2d556d8b..40da879c 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -802,6 +802,35 @@ class myDequeue{ } ``` +rust: + +```rust +impl Solution { + pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { + let mut res = vec![]; + let mut queue = VecDeque::with_capacity(k as usize); + for (i, &v) in nums.iter().enumerate() { + // 如果队列长度超过 k,那么需要移除队首过期元素 + if i - queue.front().unwrap_or(&0) == k as usize { + queue.pop_front(); + } + while let Some(&index) = queue.back() { + if nums[index] >= v { + break; + } + // 如果队列第一个元素比当前元素小,那么就把队列第一个元素弹出 + queue.pop_back(); + } + queue.push_back(i); + if i >= k as usize - 1 { + res.push(nums[queue[0]]); + } + } + res + } +} +``` +