summaryrefslogtreecommitdiff
path: root/valid-parentheses/src/main.rs
blob: 5ee7e96712763c3aa645fe1297f27c6f06d66c2d (plain)
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
fn main() {
    let tests = vec![
        ("()", true),
        ("()[]{}", true),
        ("([", false)
    ];

    for test in tests {
        println!("{} is {} should be {}", test.0, is_valid(test.0.to_string()).to_string(), test.1)
    }
}

fn is_valid(s: String) -> bool {

    let mut stack: Vec<char> = vec![]; 

    for c in s.chars() {
        match c {
            '[' | '(' | '{' => stack.push(c),
            ']' | ')' | '}' => {
                match stack.pop() {
                    Some(head) => if lookup(head).unwrap() != c {return false;},
                    None => return false
                }
            }
            _ => {}
        }
    }
    return stack.is_empty();
}

fn lookup(c: char) -> Option<char> {
    match c {
        '[' => Some(']'),
        '(' => Some(')'),
        '{' => Some('}'),
        _ => None
    }
}