Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.app
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:ide
Example:
Input: "((()))"
Output: Trueui
Input: "[()]{}"
Output: Truethis
Input: "({[)]"
Output: Falsecode
建立一個棧。
而後開始從左到右枚舉每一個字符,
遇到左括號則進棧;
遇到右括號,則出棧棧頂的元素。判斷該元素是否和當前的右括號匹配:
如不匹配,則返回 false.
如匹配,則繼續下一個循環;
判斷棧是否爲空。爲空則返回 true, 不然返回 false.input
時間複雜度爲 O(n).string
class Solution: def isValid(self, s): stack = [] matches = { "}": "{", "]": "[", ")": "(" } for c in s: if c in matches.values(): # 左括號 stack.append(c) elif c in matches.keys(): # 右括號 left = stack.pop() if left == matches[c]: continue else: return False else: continue return len(stack) == 0 # Test Program s = "()(){(())" # should return False print(Solution().isValid(s)) s = "" # should return True print(Solution().isValid(s)) s = "([{}])()" # should return True print(Solution().isValid(s))