任务一:有效的括号
题目链接:https://leetcode-cn.com/problems/valid-parentheses/
自己的答案:
1 class Solution: 2 def isValid(self, s): 3 s = list(s) 4 length = len(s) 5 6 #空字符串被认为是有效字符串 7 if length == 0: 8 return True 9 10 stringList = ['(', ')', '[', ']', '{', '}'] 11 for s_element in s: 12 if s_element not in stringList: 13 return False 14 15 counter1 = 0 16 counter2 = 0 17 counter3 = 0 18 for s_ele in s: 19 if s_ele == "(": 20 counter1 += 1 21 elif s_ele == ")": 22 counter1 -= 1 23 elif s_ele == "[": 24 counter2 += 1 25 elif s_ele == "]": 26 counter2 -= 1 27 elif s_ele == "{": 28 counter3 += 1 29 elif s_ele == "}": 30 counter3 -= 1 31 if counter1 == 0 and counter2 == 0 and counter3 == 0: 32 return True 33 else: 34 return False 35
官方答案:
1 class Solution(object): 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 8 # The stack to keep track of opening brackets. 9 stack = [] 10 11 # Hash map for keeping track of mappings. This keeps the code very clean. 12 # Also makes adding more types of parenthesis easier 13 mapping = {")": "(", "}": "{", "]": "["} 14 15 # For every bracket in the expression. 16 for char in s: 17 18 # If the character is an closing bracket 19 if char in mapping: 20 21 # Pop the topmost element from the stack, if it is non empty 22 # Otherwise assign a dummy value of '#' to the top_element variable 23 top_element = stack.pop() if stack else '#' 24 25 # The mapping for the opening bracket in our hash and the top 26 # element of the stack don't match, return False 27 if mapping[char] != top_element: 28 return False 29 else: 30 # We have an opening bracket, simply push it onto the stack. 31 stack.append(char) 32 33 # In the end, if the stack is empty, then we have a valid expression. 34 # The stack won't be empty for cases like ((() 35 return not stack