標籤:

[leetcode algorithms]題目20

20. 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.

自己寫的代碼:

利用堆棧記錄出現了那些左括弧,一旦出現右括弧就把左括弧pop出去,最後堆棧應該會變空才對。運行時間63 ms

class Solution: def isValid(self, s): if len(s) % 2 == 1: return False left = set([(, [, {]) dic = {): (, ]: [, }: {} stack = [] for char in s: if char in left: stack.append(char) else: if stack and dic[char] == stack[-1]: stack.pop() else: return False return stack == []

推薦閱讀:

Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
【LeetCode】005-最長迴文子串
單鏈表翻轉?
[leetcode algorithms]題目19
LeetCode 簡略題解 - 401~500

TAG:LeetCode |