KK's blog

每天积累多一些

0%

LeetCode 020 Valid Parentheses

LeetCode



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

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

Example 1:

Input: s = “()”
Output: true


Example 2:

Input: s = “()[]{}”
Output: true


Example 3:

Input: s = “(]”
Output: false


Example 4:

Input: s = “([)]”
Output: false


Example 5:

Input: s = “{[]}”
Output: true


Constraints:

1 <= s.length <= 10<sup>4</sup> s consists of parentheses only '()[]{}'.

题目大意:

求给定字符串是否合法括号配对。

算法思路:

括号题优先考虑用Stack

注意事项:

  1. 三种不合法情况: ‘[‘ (stack有余), ‘]’ (要匹配的时候stack为空), ‘{]’ (不匹配)

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PARENTHESES_DICT = {'(': ')', '[': ']', '{': '}'}
class Solution:
def isValid(self, s: str) -> bool:
if not s:
return False
stack = []
for char in s:
if char in '([{':
stack.append(char)
else:
if not stack:
return False
left = stack.pop()
if PARENTHESES_DICT[left] != char:
return False
return True if not stack else False

算法分析:

时间复杂度为O(n),空间复杂度O(n)

Free mock interview