简繁EN

LeetCodeNo. 083

[LeetCode with Python] 20. Valid Parentheses

Contents

Problem

Problem page: https://leetcode.com/problems/valid-parentheses/
Topics: Stack, String
Difficulty: Easy
Similar problems: (M) Generate Parentheses, (H) Longest Valid Parentheses

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


Analysis

I bet we all did this problem in college, though that version might have been a little simpler since we only had to match parentheses. Here we have three kinds of brackets to deal with, but it's still just as easy.
I use a stack to keep track of the opening brackets. Each time I see a closing bracket, I pop an opening bracket off the stack and check whether it matches the closing bracket. Once I've gone through all the brackets, I check whether the stack is empty.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:

def isMatch(self, l ,r):
return ("(" == l and ")" == r) or ("[" == l and "]" == r) or ("{" == l and "}" == r)

# @return a boolean
def isValid(self, s):
len_s = len(s)
if 0 == len(s):
return True
arr = [ ]
for ch in s:
len_arr = len(arr)
if 0 == len_arr or not self.isMatch(arr[len_arr - 1], ch):
arr.append(ch)
else:
arr.pop()
return 0 == len(arr)

Article link: https://xnerv.wang/en/leetcode-valid-parentheses/