原題地址:https://oj.leetcode.com/problems/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.
解題思路:判斷括號匹配的合法性。使用一個棧來解決問題。遇到左括號入棧,遇到右括號,檢查棧頂的左括號是否匹配,如果匹配,彈棧,如果不匹配,返回錯誤。如果棧為空,而遇到右括號,同樣返回錯誤。遍歷完后,棧如果不空,同樣返回錯誤。
代碼:
class Solution: # @return a boolean def isValid(self, s): stack = [] for i in range(len(s)): if s[i] == '(' or s[i] == '[' or s[i] == '{': stack.append(s[i]) if s[i] == ')': if stack == [] or stack.pop() != '(': return False if s[i] == ']': if stack == [] or stack.pop() != '[': return False if s[i] == '}': if stack == [] or stack.pop() != '{': return False if stack: return False else: return True
