Leecode 0020. Valid Parentheses
20. Valid Parentheses
Given a string s
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.
- Every close bracket has a corresponding open bracket of the same type.
题目大意
给定一个只包含 '('
、')'
、'{'
、'}'
、'['
和 ']'
的字符串,判断该字符串是否有效。有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
解题思路
判断括号有效性的经典解法是使用栈数据结构,核心思路如下:
- 遍历字符串中的每个字符。
- 遇到左括号(
'('
、'{'
、'['
)时,将其压入栈中。 - 遇到右括号时:
- 若栈为空,说明没有对应的左括号,直接返回
false
。 - 弹出栈顶元素,检查是否与当前右括号匹配(如
')'
对应'('
)。 - 若不匹配,返回
false
。
- 若栈为空,说明没有对应的左括号,直接返回
- 遍历结束后,若栈为空,说明所有左括号都有匹配的右括号,返回
true
;否则返回false
。
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.