题目描述:
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(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis 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
解题思路:
dp[i]表示i位置之前的单个括号的数量。当遇到"("时,dp[i]++,遇到")"dp[i]--,当dp[i] < 0,表示,i之前需要匹配加入的"("的数量,因为")"多了无法通过在后面加入"("进行匹配。此时dp[i] = 0,在最终结果加上这个数量。
,dp[i] = 0,res += 1,if dp[i] < 0,
Python代码:
class Solution:
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
tem, res = 0, 0
for x in S:
if x == '(':
tem += 1
else: tem -= 1
if tem < 0:
res += 1
tem = 0
return res + tem


本文深入探讨了如何通过动态规划解决括号匹配问题,详细解释了如何计算最小括号添加数以使字符串有效。通过具体实例,展示了算法的运行过程和优化策略。
657

被折叠的 条评论
为什么被折叠?



