📜  平衡括号的成本

📅  最后修改于: 2021-04-26 18:00:59             🧑  作者: Mango

当每个开括号都具有闭括号时,如“()()”或“(())”或“(()())”等,括号被认为是平衡的。不正确的平衡包括“)(”或“)) (((”等。这里的任务是以最小的成本来校正括号的顺序,并且将括号移动一个以上的括号会花费1。如果无法平衡括号,则打印-1 。
例子 :

算法 :

  1. 将花括号存储在字符串。
  2. 运行一个字符串大小循环,以存储左括号和右括号的计数。
  3. 检查打开撑杆的数量是否等于关闭撑杆的数量。
  4. 如果花括号不相等,则打印-1表示字符串无法平衡。否则,进一步进行。
  5. 最初,在0索引处检查字符串是否包含开头括号或结尾括号。如果我们开括号然后存储阵列中的+1索引0,否则,如果右括号存在,则地方-1 0指标。
  6. 现在运行一个从第一个索引到数组长度的循环。
    • 如果在索引i处存在大括号,则将+1添加到先前索引(即i-1)的值并将总和存储在索引i中。
    • 如果在索引i处存在右花括号,则将上一个索引(即i-1)的值加-1,并将和存储在索引i中。
    • 如果索引i处的值为负,即小于0,则将array [i]的绝对值添加到变量中(以下程序中的ans)。
  7. 最后,我们得到变量ans中的最小成本。

下面是上述方法的实现:

C++
// CPP code to calculate the minimum cost
// to make the given parentheses balanced
#include 
using namespace std;
 
int costToBalance(string s)
{
    if (s.length() == 0)
        cout << 0 << endl;
 
    // To store absolute count of
    // balanced and unbalanced parenthesis
    int ans = 0;
 
    // o(open bracket) stores count of '(' and
    // c(close bracket) stores count of ')'
    int o = 0, c = 0;
 
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(')
            o++;
        if (s[i] == ')')
            c++;
    }
 
    if (o != c)
        return -1;
 
    int a[s.size()];
    if (s[0] == '(')
        a[0] = 1;
    else
        a[0] = -1;
 
    if (a[0] < 0)
        ans += abs(a[0]);
 
    for (int i = 1; i < s.length(); i++) {
        if (s[i] == '(')
            a[i] = a[i - 1] + 1;
        else
            a[i] = a[i - 1] - 1;
        if (a[i] < 0)
            ans += abs(a[i]);
    }
 
    return ans;
}
 
// Driver code
int main()
{
    string s;
    s = ")))(((";
 
    cout << costToBalance(s) << endl;
 
    s = "))((";
    cout << costToBalance(s) << endl;
 
    return 0;
}


Java
// Java code to calculate the
// minimum cost to make the
// given parentheses balanced
import java.io.*;
 
class GFG
{
    static int costToBalance(String s)
    {
        if (s.length() == 0)
            System.out.println(0);
     
        // To store absolute count
        // of balanced and unbalanced
        // parenthesis
        int ans = 0;
     
        // o(open bracket) stores count
        // of '(' and c(close bracket)
        // stores count of ')'
        int o = 0, c = 0;
     
        for (int i = 0; i < s.length(); i++)
        {
            if (s.charAt(i) == '(')
                o++;
            if (s.charAt(i) == ')')
                c++;
        }
     
        if (o != c)
            return -1;
     
        int []a = new int[s.length()];
        if (s.charAt(0) == '(')
            a[0] = 1;
        else
            a[0] = -1;
     
        if (a[0] < 0)
            ans += Math.abs(a[0]);
     
        for (int i = 1; i < s.length(); i++)
        {
            if (s.charAt(i) == '(')
                a[i] = a[i - 1] + 1;
            else
                a[i] = a[i - 1] - 1;
            if (a[i] < 0)
                ans += Math.abs(a[i]);
        }
     
        return ans;
    }
     
    // Driver code
    public static void main(String args[])
    {
        String s;
        s = ")))(((";
     
        System.out.println(costToBalance(s));
     
        s = "))((";
        System.out.println(costToBalance(s));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Python3
# Python 3 code to calculate the minimum cost
# to make the given parentheses balanced
def costToBalance(s):
    if (len(s) == 0):
        print(0)
 
    # To store absolute count of
    # balanced and unbalanced parenthesis
    ans = 0
 
    # o(open bracket) stores count of '(' and
    # c(close bracket) stores count of ')'
    o = 0
    c = 0
 
    for i in range(len(s)):
        if (s[i] == '('):
            o += 1
        if (s[i] == ')'):
            c += 1
 
    if (o != c):
        return -1
 
    a = [0 for i in range(len(s))]
    if (s[0] == '('):
        a[0] = 1
    else:
        a[0] = -1
 
    if (a[0] < 0):
        ans += abs(a[0])
 
    for i in range(1, len(s)):
        if (s[i] == '('):
            a[i] = a[i - 1] + 1
        else:
            a[i] = a[i - 1] - 1
        if (a[i] < 0):
            ans += abs(a[i])
 
    return ans
 
# Driver code
if __name__ == '__main__':
    s = ")))((("
 
    print(costToBalance(s))
    s = "))(("
    print(costToBalance(s))
     
# This code is contributed by
# Surendra_Gangwar


C#
// C# code to calculate the
// minimum cost to make the
// given parentheses balanced
using System;
 
class GFG
{
    static int costToBalance(string s)
    {
        if (s.Length == 0)
            Console.WriteLine(0);
     
        // To store absolute count
        // of balanced and unbalanced
        // parenthesis
        int ans = 0;
     
        // o(open bracket) stores count
        // of '(' and c(close bracket)
        // stores count of ')'
        int o = 0, c = 0;
     
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
                o++;
            if (s[i] == ')')
                c++;
        }
     
        if (o != c)
            return -1;
     
        int []a = new int[s.Length];
        if (s[0] == '(')
            a[0] = 1;
        else
            a[0] = -1;
     
        if (a[0] < 0)
            ans += Math.Abs(a[0]);
     
        for (int i = 1; i < s.Length; i++)
        {
            if (s[i] == '(')
                a[i] = a[i - 1] + 1;
            else
                a[i] = a[i - 1] - 1;
            if (a[i] < 0)
                ans += Math.Abs(a[i]);
        }
     
        return ans;
    }
     
    // Driver code
    static void Main()
    {
        string s;
        s = ")))(((";
     
        Console.WriteLine (costToBalance(s));
     
        s = "))((";
        Console.WriteLine (costToBalance(s));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


输出:
9
4

时间复杂度: O(N),N =字符串长度

辅助空间: O(N)