rs-02-balanced
1.000
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
// 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