0020. Valid Parentheses

20. Valid Parentheses #

Problem #

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:


Input: "()"
Output: true

Example 2:


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

Example 3:


Input: "(]"
Output: false

Example 4:


Input: "([)]"
Output: false

Example 5:


Input: "{[]}"
Output: true

Main Idea #

Parentheses matching problem.

Solution Approach #

When encountering a left bracket, push it onto the stack. When encountering a right bracket and the top of the stack is the corresponding left bracket, pop the top element from the stack. Finally, check whether there are any other elements left in the stack. If it is empty, then it matches.

It should be noted that an empty string satisfies parentheses matching, so output true.

Code #


package leetcode

func isValid(s string) bool {
	// Return true directly for an empty string
	if len(s) == 0 {
		return true
	}
	stack := make([]rune, 0)
	for _, v := range s {
		if (v == '[') || (v == '(') || (v == '{') {
			stack = append(stack, v)
		} else if ((v == ']') && len(stack) > 0 && stack[len(stack)-1] == '[') ||
			((v == ')') && len(stack) > 0 && stack[len(stack)-1] == '(') ||
			((v == '}') && len(stack) > 0 && stack[len(stack)-1] == '{') {
			stack = stack[:len(stack)-1]
		} else {
			return false
		}
	}
	return len(stack) == 0
}



Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文