← run

rs-02-balanced

1.000
7/7 tests· algorithms

Proposed solution

```rust
// src/lib.rs

pub fn is_balanced(input: &str) -> bool {
    let mut stack = Vec::new();

    for c in input.chars() {
        match c {
            '(' | '[' | '{' => stack.push(c),
            ')' | ']' | '}' => {
                match c {
                    ')' => {
                        if stack.last() != Some(&'(') {
                            return false;
                        }
                        stack.pop();
                    }
                    ']' => {
                        if stack.last() != Some(&'[') {
                            return false;
                        }
                        stack.pop();
                    }
                    '}' => {
                        if stack.last() != Some(&'{') {
                            return false;
                        }
                        stack.pop();
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    stack.is_empty()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_balanced() {
        assert_eq!(is_balanced("()[]{}"), true);
        assert_eq!(is_balanced("([{}])"), true);
        assert_eq!(is_balanced("(a + [b * c]) - {d}"), true);
        assert_eq!(is_balanced("(]"), false);
        assert_eq!(is_balanced("([)]"), false);
        assert_eq!(is_balanced("("), false);
        assert_eq!(is_balanced(")("), false);
        assert_eq!(is_balanced(""), true);
    }
}
```

Test output (stdout)


running 1 test
.
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 6 tests
......
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.