โ† run

rs-02-balanced

1.000
6/6 testsยท algorithms
Challenge ยท difficulty 2/5
# Balanced brackets

Implement the library file **`src/lib.rs`** exposing:

```rust
pub fn is_balanced(input: &str) -> bool
```

Return `true` if and only if the brackets `()`, `[]`, and `{}` in `input` are
correctly balanced and nested. Every opening bracket must be closed by a matching
closing bracket in the right order. Any closing bracket must match the most
recently opened, still-unclosed bracket.

- Non-bracket characters are ignored.
- The empty string is balanced (returns `true`).

Examples:

- `is_balanced("")` โ†’ `true`
- `is_balanced("()[]{}")` โ†’ `true`
- `is_balanced("([{}])")` โ†’ `true`
- `is_balanced("(a + [b * c]) - {d}")` โ†’ `true`
- `is_balanced("(]")` โ†’ `false`
- `is_balanced("([)]")` โ†’ `false`
- `is_balanced("(")` โ†’ `false`
- `is_balanced(")(")` โ†’ `false`

Tests live in `tests/` and call it as `challenge::is_balanced`.
tests/balanced.rs
use challenge::is_balanced;

#[test]
fn empty_is_balanced() {
    assert!(is_balanced(""));
}

#[test]
fn simple_pairs() {
    assert!(is_balanced("()[]{}"));
    assert!(is_balanced("([{}])"));
}

#[test]
fn ignores_non_brackets() {
    assert!(is_balanced("(a + [b * c]) - {d}"));
    assert!(is_balanced("no brackets at all"));
}

#[test]
fn mismatched_type() {
    assert!(!is_balanced("(]"));
    assert!(!is_balanced("{)"));
}

#[test]
fn wrong_nesting_order() {
    assert!(!is_balanced("([)]"));
}

#[test]
fn unclosed_or_unopened() {
    assert!(!is_balanced("("));
    assert!(!is_balanced(")("));
    assert!(!is_balanced("(()"));
}
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.
Proposed solution
```rust
pub fn is_balanced(input: &str) -> bool {
    let mut stack = Vec::new();
    let mut bracket_pairs = std::collections::HashMap::new();
    bracket_pairs.insert(')', '(');
    bracket_pairs.insert(']', '[');
    bracket_pairs.insert('}', '{');

    for c in input.chars() {
        if c == '(' || c == '[' || c == '{' {
            stack.push(c);
        } else if let Some(&expected) = bracket_pairs.get(&c) {
            if stack.pop() != Some(expected) {
                return false;
            }
        }
    }

    stack.is_empty()
}
```

Test output (stdout)


running 0 tests

test result: ok. 0 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