题解 | #缺失的括号#
缺失的括号
https://www.nowcoder.com/practice/cb9c921685574659937629a4d64b091f
# import sys # for line in sys.stdin: # a = line.split() # print(int(a[0]) + int(a[1])) sequence = input().strip() def missing_parentheses(s): count = 0 stack = [] # 用一个栈来放左括号,如果右括号匹配上就出栈,遍历完成后栈里剩下的数量就是少的左括号数量 # 如果读到右括号时栈是空的,说明没有匹配上,计数一次 # 最后两个值相加,就是缺少的数量 for i in sequence: if i == ')': if not stack: count += 1 else: stack.pop() else: stack.append('(') return len(stack) + count print(missing_parentheses(sequence))