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
pub fn is_balanced(input: &str) -> bool {
let mut stack: Vec<char> = Vec::new();
for ch in input.chars() {
match ch {
'(' | '[' | '{' => stack.push(ch),
')' => {
if stack.pop() != Some('(') {
return false;
}
}
']' => {
if stack.pop() != Some('[') {
return false;
}
}
'}' => {
if stack.pop() != Some('{') {
return false;
}
}
_ => {} // Ignore non-bracket characters
}
}
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
Reasoning (chain-of-thought)
The user wants me to implement a Rust library file `src/lib.rs` that contains a function `is_balanced` which checks if brackets `()`, `[]`, and `{}` are balanced and properly nested in a given string.
Key requirements:
1. Function signature: `pub fn is_balanced(input: &str) -> bool`
2. Only brackets `()`, `[]`, `{}` matter
3. Non-bracket characters are ignored
4. Empty string returns `true`
5. Must be properly nested (LIFO order)
This is a classic stack-based problem:
- When we encounter an opening bracket, push it onto a stack
- When we encounter a closing bracket, check if it matches the top of the stack
- If it matches, pop from stack; if not, return false
- At the end, the stack should be empty
Let me write the implementation:
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack: Vec<char> = Vec::new();
for ch in input.chars() {
match ch {
'(' | '[' | '{' => stack.push(ch),
')' => {
if stack.pop() != Some('(') {
return false;
}
}
']' => {
if stack.pop() != Some('[') {
return false;
}
}
'}' => {
if stack.pop() != Some('{') {
return false;
}
}
_ => {} // Ignore non-bracket characters
}
}
stack.is_empty()
}
```
This should work correctly for all the test cases:
- `""` โ empty stack, returns true
- `"()[]{}"` โ all pairs match, stack empty at end, returns true
- `"([{}])"` โ nested correctly, returns true
- `"(a + [b * c]) - {d}"` โ non-bracket chars ignored, brackets balanced, returns true
- `"(]"` โ `)` doesn't match `[`, returns false
- `"([)]"` โ `)` doesn't match `[` (top is `[`), returns false
- `"("` โ stack not empty at end, returns false
- `")("` โ `)` has empty stack, returns false
I'll create the file structure with `src/lib.rs` and potentially a test file in `tests/`.