简繁EN

LeetCodeNo. 083

【LeetCode with Python】 20. Valid Parentheses

目錄

題目

原題頁面:https://leetcode.com/problems/valid-parentheses/
題目型別:Stack, String
難度評價:Easy
類似題目:(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.


分析

大家肯定在大學時都做過這道題目吧,不過可能相對簡單一點,只涉及小括號的配對,這裡需要考慮三種括號,不過還是一樣的簡單。
用棧來記錄遇到的左括號,每次遇到右括號,就從棧中彈出一個左括號,看是不是與該右括號是匹配的。最後當所有的括號都遍歷完成時,檢查棧是否為空。


程式碼

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)

本文地址:https://xnerv.wang/zh-tw/leetcode-valid-parentheses/