DevPath

← All problems

Valid Parentheses

Easy stack · strings

Description

Return true if every opening bracket is closed by the matching bracket in the correct order.

Constraints

0 <= length <= 100000; characters are ()[]{}

Examples

Input: s = "()[]{}"

Output: true

Input: s = "(]"

Output: false

Hints (1)
  • Push openers; on a closer, the top of the stack must match.

Solutions

Stack of open brackets. · Time O(n) · Space O(n)

func isValid(s string) bool {
    pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
    var stack []rune
    for _, c := range s {
        if open, ok := pairs[c]; ok {
            if len(stack) == 0 || stack[len(stack)-1] != open {
                return false
            }
            stack = stack[:len(stack)-1]
        } else {
            stack = append(stack, c)
        }
    }
    return len(stack) == 0
}

Create a free account to submit solutions, track progress and save problems.

Create account