LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給定一個只包括'(',')','{','}','[',']'
的字符串,判斷字符串是否有效。
有效字符串需滿足:
1. 左括號必須用相同類型的右括號閉合。
2. 左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
示例:
- 示例 1:
輸入: "()" 輸出: true
- 示例 2:
輸入: "()[]{}" 輸出: true
- 示例 3:
輸入: "(]" 輸出: false
- 示例 4:
輸入: "([)]" 輸出: false
- 示例 5:
輸入: "{[]}" 輸出: true
代碼
方法一: 堆棧 題解
執行用時:32 ms, 在所有 Python3 提交中擊敗了97.36%的用戶
內存消耗:13.8 MB, 在所有 Python3 提交中擊敗了5.22%的用戶
class Solution:
def isValid(self, s: str) -> bool:
dic = {')':'(',']':'[','}':'{'}
stack = []
for i in s:
if stack and i in dic:
if stack[-1] == dic[i]: stack.pop()
else: return False
else: stack.append(i)
return not stack
"""
For Example: input: s = "{[]}"
output: true
"""
s = "{[]}"
solution = Solution()
result = solution.isValid(s)
print('輸出爲:', result)
參考
- https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/