-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0385_mini_parser.rs
More file actions
77 lines (72 loc) · 2.34 KB
/
s0385_mini_parser.rs
File metadata and controls
77 lines (72 loc) · 2.34 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#![allow(unused)]
pub struct Solution {}
#[derive(Debug, PartialEq, Eq)]
pub enum NestedInteger {
Int(i32),
List(Vec<NestedInteger>),
}
impl Solution {
// Time O(N), Space O(N) Iterative Solution
pub fn deserialize(s: String) -> NestedInteger {
if !&s.starts_with("[") {
return NestedInteger::Int(s.parse::<i32>().unwrap());
}
let mut stack: Vec<NestedInteger> = vec![];
let mut digit_str: String = String::new();
for c in s.chars() {
if c == '[' {
stack.push(NestedInteger::List(vec![]));
} else if c == '-' || c.is_digit(10) {
digit_str.push(c);
} else if c == ',' {
if !digit_str.is_empty() {
if let Some(v) = stack.last_mut() {
if let NestedInteger::List(n) = v {
n.push(NestedInteger::Int(digit_str.parse::<i32>().unwrap()));
}
}
digit_str.truncate(0);
}
} else {
if !digit_str.is_empty() {
if let Some(v) = stack.last_mut() {
if let NestedInteger::List(n) = v {
n.push(NestedInteger::Int(digit_str.parse::<i32>().unwrap()));
}
}
digit_str.truncate(0);
}
let n = stack.pop().unwrap();
if stack.is_empty() {
return n;
} else if let Some(v) = stack.last_mut() {
if let NestedInteger::List(nst) = v {
nst.push(n);
}
}
}
}
NestedInteger::Int(-1)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_385() {
assert_eq!(
Solution::deserialize("324".to_string()),
NestedInteger::Int(324)
);
assert_eq!(
Solution::deserialize("[123,[456,[789]]]".to_string()),
NestedInteger::List(vec![
NestedInteger::Int(123),
NestedInteger::List(vec![
NestedInteger::Int(456),
NestedInteger::List(vec![NestedInteger::Int(789)])
])
])
);
}
}