📜  使表达式平衡所需的最小括号反转数|套装 – 2

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

使表达式平衡所需的最小括号反转数|套装 – 2

给定一个只有 '}' 和 '{' 的表达式。表达可能不平衡。任务是找到最小数量的括号反转以使表达式平衡。
例子:

Input : exp = "}{"
Output : 2
We need to change '}' to '{' and '{' to
'}' so that the expression becomes balanced, 
the balanced expression is '{}'

Input : exp = "}{{}}{{{"
Output : 3
The balanced expression is "{{{}}{}}"

上一篇文章中讨论的解决方案需要 O(n) 额外空间。这个问题可以用常数空间来解决。
这个想法是使用两个变量openclose ,其中open表示不平衡的左括号数, close表示不平衡的右括号数。
遍历字符串,如果当前字符是左括号增量open 。如果当前字符是右括号,则检查是否有不平衡的左括号( open > 0)。如果是,则减少打开,否则增加关闭,因为此支架不平衡。
以下是上述方法的实现:

C++
// C++ program to find minimum number of
// reversals required to balance an expression
#include 
using namespace std;
 
// Returns count of minimum reversals for making
// expr balanced. Returns -1 if expr cannot be
// balanced.
int countMinReversals(string expr)
{
    int len = expr.length();
 
    // length of expression must be even to make
    // it balanced by using reversals.
    if (len % 2)
        return -1;
 
    // To store number of reversals required.
    int ans = 0;
 
    int i;
 
    // To store number of unbalanced opening brackets.
    int open = 0;
 
    // To store number of unbalanced closing brackets.
    int close = 0;
 
    for (i = 0; i < len; i++) {
 
        // If current bracket is open then increment
        // open count.
        if (expr[i] == '{')
            open++;
 
        // If current bracket is close, check if it
        // balances opening bracket. If yes then
        // decrement count of unbalanced opening
        // bracket else increment count of
        // closing bracket.
        else {
            if (!open)
                close++;
            else
                open--;
        }
    }
 
    ans = (close / 2) + (open / 2);
 
    // For the case: "}{" or when one closing and
    // one opening bracket remains for pairing, then
    // both need to be reversed.
    close %= 2;
    open %= 2;
    if (close)
        ans += 2;
 
    return ans;
}
 
// Driver Code
int main()
{
    string expr = "}}{{";
 
    cout << countMinReversals(expr);
 
    return 0;
}


Java
// Java program to find minimum number of
// reversals required to balance an expression
class GFG
{
 
// Returns count of minimum reversals for making
// expr balanced. Returns -1 if expr cannot be
// balanced.
static int countMinReversals(String expr)
{
    int len = expr.length();
 
    // length of expression must be even to make
    // it balanced by using reversals.
    if (len % 2 != 0)
        return -1;
 
    // To store number of reversals required.
    int ans = 0;
 
    int i;
 
    // To store number of unbalanced opening brackets.
    int open = 0;
 
    // To store number of unbalanced closing brackets.
    int close = 0;
 
    for (i = 0; i < len; i++)
    {
 
        // If current bracket is open then increment
        // open count.
        if (expr.charAt(i) == '{')
            open++;
 
        // If current bracket is close, check if it
        // balances opening bracket. If yes then
        // decrement count of unbalanced opening
        // bracket else increment count of
        // closing bracket.
        else
        {
            if (open == 0)
                close++;
            else
                open--;
        }
    }
 
    ans = (close / 2) + (open / 2);
 
    // For the case: "}{" or when one closing and
    // one opening bracket remains for pairing, then
    // both need to be reversed.
    close %= 2;
    open %= 2;
    if (close != 0)
        ans += 2;
 
    return ans;
}
 
// Driver Code
public static void main(String args[])
{
    String expr = "}}{{";
 
    System.out.println(countMinReversals(expr));
}
}
 
// This code is contributed by Arnab Kundu


Python3
# Python3 program to find minimum number of
# reversals required to balance an expression
 
# Returns count of minimum reversals for
# making expr balanced. Returns -1 if
# expr cannot be balanced.
def countMinReversals(expr):
 
    length = len(expr)
 
    # length of expression must be even to
    # make it balanced by using reversals.
    if length % 2:
        return -1
 
    # To store number of reversals required.
    ans = 0
 
    # To store number of unbalanced
    # opening brackets.
    open = 0
 
    # To store number of unbalanced
    # closing brackets.
    close = 0
 
    for i in range(0, length):
 
        # If current bracket is open
        # then increment open count.
        if expr[i] == "":
            open += 1
 
        # If current bracket is close, check if it
        # balances opening bracket. If yes then
        # decrement count of unbalanced opening
        # bracket else increment count of
        # closing bracket.
        else:
            if not open:
                close += 1
            else:
                open -= 1
         
    ans = (close // 2) + (open // 2)
 
    # For the case: "" or when one closing
    # and one opening bracket remains for
    # pairing, then both need to be reversed.
    close %= 2
    open %= 2
     
    if close > 0:
        ans += 2
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    expr = "}}{{"
    print(countMinReversals(expr))
 
# This code is contributed by Rituraj Jain


C#
// C# program to find minimum number of
// reversals required to balance an expression
using System;
     
class GFG
{
 
// Returns count of minimum reversals for making
// expr balanced. Returns -1 if expr cannot be
// balanced.
static int countMinReversals(String expr)
{
    int len = expr.Length;
 
    // length of expression must be even to make
    // it balanced by using reversals.
    if (len % 2 != 0)
        return -1;
 
    // To store number of reversals required.
    int ans = 0;
 
    int i;
 
    // To store number of unbalanced opening brackets.
    int open = 0;
 
    // To store number of unbalanced closing brackets.
    int close = 0;
 
    for (i = 0; i < len; i++)
    {
 
        // If current bracket is open then increment
        // open count.
        if (expr[i] == '{')
            open++;
 
        // If current bracket is close, check if it
        // balances opening bracket. If yes then
        // decrement count of unbalanced opening
        // bracket else increment count of
        // closing bracket.
        else
        {
            if (open == 0)
                close++;
            else
                open--;
        }
    }
 
    ans = (close / 2) + (open / 2);
 
    // For the case: "}{" or when one closing and
    // one opening bracket remains for pairing, then
    // both need to be reversed.
    close %= 2;
    open %= 2;
    if (close != 0)
        ans += 2;
 
    return ans;
}
 
// Driver Code
public static void Main(String []args)
{
    String expr = "}}{{";
 
    Console.WriteLine(countMinReversals(expr));
}
}
 
// This code contributed by Rajput-Ji


Javascript


输出:
2

时间复杂度: O(N),其中 N 是字符串的长度。
辅助空间: O(1)