題目
原題頁面: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 | class Solution: |
