📌  相关文章
📜  要添加的最小括号数以使其有效

📅  最后修改于: 2022-05-13 01:57:07.603000             🧑  作者: Mango

要添加的最小括号数以使其有效

给定一个带括号 '(' 或 ')' 的字符串S,其中, 0\leq len(S)\leq 1000  .任务是找到最小数量的括号“(”或“)”(在任何位置),我们必须添加以使生成的括号字符串有效。
例子:

Input: str = "())"
Output: 1
One '(' is required at beginning.

Input: str = "((("
Output: 3
Three ')' is required at end.

方法:我们跟踪字符串的平衡,即“(”的数量减去“)”的数量。如果一个字符串的余额为 0,则该字符串是有效的,并且每个前缀都有非负余额。
现在,考虑 S 的每个前缀的余额。如果它曾经是负数(例如,-1),我们必须在开头添加一个 '(' 括号。此外,如果 S 的余额是正数(例如,+P) ,我们必须在末尾添加 P 次 ')' 括号。
下面是上述方法的实现:

C++
// C++ Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
#include 
using namespace std;
 
// Function to return required minimum number
int minParentheses(string p)
{
 
    // maintain balance of string
    int bal = 0;
    int ans = 0;
 
    for (int i = 0; i < p.length(); ++i) {
 
        bal += p[i] == '(' ? 1 : -1;
 
        // It is guaranteed bal >= -1
        if (bal == -1) {
            ans += 1;
            bal += 1;
        }
    }
 
    return bal + ans;
}
 
// Driver code
int main()
{
 
    string p = "())";
 
    // Function to print required answer
    cout << minParentheses(p);
 
    return 0;
}


Java
// Java Program to find minimum number of '(' or ')'
// must be added to make Parentheses string valid.
 
public class GFG {
 
    // Function to return required minimum number
    static int minParentheses(String p)
    {
       
        // maintain balance of string
        int bal = 0;
        int ans = 0;
       
        for (int i = 0; i < p.length(); ++i) {
       
            bal += p.charAt(i) == '(' ? 1 : -1;
       
            // It is guaranteed bal >= -1
            if (bal == -1) {
                ans += 1;
                bal += 1;
            }
        }
       
        return bal + ans;
    }
     
    public static void main(String args[])
    {
        String p = "())";
         
        // Function to print required answer
        System.out.println(minParentheses(p));
       
    }
    // This code is contributed by ANKITRAI1
}


Python3
# Python3 Program to find
# minimum number of '(' or ')'
# must be added to make Parentheses
# string valid.
 
# Function to return required
# minimum number
def minParentheses(p):
     
    # maintain balance of string
    bal=0
    ans=0
    for i in range(0,len(p)):
        if(p[i]=='('):
            bal+=1
        else:
            bal+=-1
             
        # It is guaranteed bal >= -1
        if(bal==-1):
            ans+=1
            bal+=1
    return bal+ans
 
# Driver code
if __name__=='__main__':
    p = "())"
     
# Function to print required answer
    print(minParentheses(p))
     
# this code is contributed by
# sahilshelangia


C#
// C# Program to find minimum number
// of '(' or ')' must be added to
// make Parentheses string valid.
using System;
 
class GFG
{
// Function to return required
// minimum number
static int minParentheses(string p)
{
 
    // maintain balance of string
    int bal = 0;
    int ans = 0;
 
    for (int i = 0; i < p.Length; ++i)
    {
 
        bal += p[i] == '(' ? 1 : -1;
 
        // It is guaranteed bal >= -1
        if (bal == -1)
        {
            ans += 1;
            bal += 1;
        }
    }
 
    return bal + ans;
}
 
// Driver code
public static void Main()
{
    string p = "())";
 
    // Function to print required answer
    Console.WriteLine(minParentheses(p));
}
}
 
// This code is contributed
// by Kirti_Mangal


PHP
= -1
        if ($bal == -1)
        {
            $ans += 1;
            $bal += 1;
        }
    }
 
    return $bal + $ans;
}
 
// Driver code
$p = "())";
 
// Function to print required answer
echo minParentheses($p);
 
// This code is contributed by ita_c
?>


Javascript


输出:
1

时间复杂度: O(N),其中 N 是 S 的长度。
空间复杂度: O(1)。