problems(rs): add “946. Validate Stack Sequences”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-04-13 19:24:05 +02:00
parent 551b7819cc
commit 2c3aa74565
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,56 @@
struct Solution {}
impl Solution {
pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut stack: Vec<i32> = vec![];
let mut i = 0;
let mut j = 0;
loop {
// If the top is to be popped, pop it
if let Some(&top) = stack.last() {
if j < popped.len() && top == popped[j] {
stack.pop();
j += 1;
continue;
}
}
// If I have an element that can be pushed, push it
if i < pushed.len() {
stack.push(pushed[i]);
i += 1;
continue;
}
// If I can't pop nor push, it's done or screwed up
break;
}
// If it's correct simulation, stack must be empty
stack.is_empty()
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn success() {
assert!(Solution::validate_stack_sequences(
vec![1, 2, 3, 4, 5],
vec![4, 5, 3, 2, 1]
));
}
#[test]
fn fail() {
assert!(!Solution::validate_stack_sequences(
vec![1, 2, 3, 4, 5],
vec![4, 3, 5, 1, 2]
));
}
}