-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvalidate-stack-sequences.rs
50 lines (41 loc) · 1.28 KB
/
validate-stack-sequences.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn validate_stack_sequences1(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let (mut index1, mut index2) = (0, 0);
let mut stack = vec![];
while index1 < pushed.len() || index2 < pushed.len() {
if index1 < pushed.len()
&& (stack.is_empty() || *stack.last().unwrap() != popped[index2])
{
stack.push(pushed[index1]);
index1 += 1;
} else {
match stack.pop() {
Some(x) if x == popped[index2] => {
index2 += 1;
}
_ => return false,
}
}
}
stack.is_empty()
}
pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut index = 0;
let mut stack = vec![];
for i in pushed {
stack.push(i);
while let Some(&x) = stack.last() {
if x == popped[index] {
stack.pop();
index += 1;
} else {
break;
}
}
}
stack.is_empty()
}
}