albertonline· portal
blind75

Valid Parentheses: Ensuring Correct Closure and Nesting

Jan 14, 2024 · Solving the Valid Parentheses problem by checking if a string containing various types of brackets is properly closed and nested.

The "Valid Parentheses" problem involves determining whether a string made up of parentheses, brackets, and braces is valid in terms of closure and nesting.

Problem Statement

Given a string containing characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, meaning "()" and "()[]{}" are valid, but "(]" and "([)]" are not.

Example

  • Input: "()[]{}"
  • Output: true
  • Input: "(]"
  • Output: false

Solution Approach - Stack Utilization (typescript)

typescript

Breaking Down the Solution


  • Using a Stack: A stack is used to keep track of opening brackets.
  • Map for Mappings: A map holds the pairs of corresponding opening and closing brackets.
  • Validating Closure: For each closing bracket, check if the top of the stack is the corresponding opening bracket. If not, the string is invalid.
  • Empty Stack: If the stack is empty at the end, the string is valid.

Conclusion


The Valid Parentheses problem is a classic example of using a stack to ensure proper closure and nesting of brackets in a string. It's a fundamental exercise in balancing and ordering in data structures.

Rust Solution

rust

match on each char with or-patterns ('(' | '{' | '[') replaces the TS map lookup entirely. Because stack.pop() returns an Option, the comparison stack.pop() != Some('(') folds the empty-stack case into the same equality — an empty Vec pops to None, which never equals Some('('), so no separate length guard is needed the way the TS version reaches for stack.length === 0 ? "#" : .... The _ => return false arm keeps the match exhaustive by rejecting any non-bracket character, and the bare stack.is_empty() is returned directly as the result.

Go Solution

go

range s iterates the string by rune, which is why the stack is declared var stack []rune — a nil slice appended to directly with append(stack, c) to push. Go has no pop that signals emptiness, so each closing case guards len(stack) == 0 before peeking the top via stack[len(stack)-1], then pops by re-slicing stack = stack[:len(stack)-1]. The switch matches several openers in one case '(', '{', '[' and, without C-style fallthrough, needs no break; unlike Rust's _ arm there is no default, so any non-bracket rune is silently skipped rather than rejected.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.