【LeetCode】921. Minimum Add to Make Parentheses Valid 解題報告(Python)
題目描述:
Given a string S of ‘(’ and ‘)’ parentheses, we add the minimum number of parentheses ( ‘(’ or ‘)’, and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
- It is the empty string, or
- It can be written as
AB
(A
concatenated withB
A
andB
are valid strings, or - It can be written as
(A)
, whereA
is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
Example 1:
Input: "())"
Output: 1
Example 2:
Input: "((("
Output: 3
Example 3:
Input: "()" Output: 0
Example 4:
Input: "()))(("
Output: 4
Note:
- S.length <= 1000
- S only consists of ‘(’ and ‘)’ characters.
題目大意
求最少新增幾個括號才能使得整個表示式是合法的括號表示式。
解題方法
遇到括號匹配題一般想到用棧。這題也不例外。
同樣是對字串進行一次遍歷,如果遍歷到的位置是左括號,那麼要進行判斷:
- 如果棧頂是右括號,那麼說明判斷前面字串缺少了幾個括號
- 否則,需要直接進棧
如果遍歷到的位置是右括號,那麼直接進棧。
我花了半個小時才把這個題做出來啊,錯誤的地方就在於左括號的判斷上。第一,判斷前面缺少幾個括號的時候,我把棧所有的元素全部退棧了,這樣就錯誤了,因為可能前面部分匹配,再往前的左括號需要等待後面的右括號來了之後才能判斷。所以,這個問題的解決方法是如果cnt == 0,就不再退棧了。第二,我把stack.append(’(’)寫錯位置了,事實上,只要出現新的左括號,這個左括號一定進棧。由於我太愚蠢了,把進棧這步放在了對棧的判斷裡面,這樣就導致了不符合棧的判斷條件的地方就沒把左括號放進去。。這個是不應該犯的錯誤。
時間複雜度是O(N),空間複雜度是O(N)。
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
if not S: return 0
stack = []
res = 0
for i, s in enumerate(S):
if '(' == s:
if stack and (stack[-1] == ')'):
cnt = 0
while stack:
if stack.pop() == ')':
cnt -= 1
else:
cnt += 1
if cnt == 0:
break
res += abs(cnt)
stack.append('(')
else:
stack.append(')')
cnt = 0
while stack:
if stack.pop() == ')':
cnt -= 1
else:
cnt += 1
res += abs(cnt)
return res
參考資料:
日期
2018 年 10 月 14 日 —— 周賽做出來3個題,開心