在C ++中平衡括号的成本

在本教程中,我们将讨论一个寻找平衡括号的成本的程序。

为此,我们将提供一系列的括号。我们的任务是通过将方程式中的括号移动一号来平衡括号中的内容,如果无法进行平衡,则打印-1。

示例

#include <bits/stdc++.h>
using namespace std;
int costToBalance(string s) {
   if (s.length() == 0)
      cout << 0 << endl;
   //存储开张数量和
   //右括号
   int ans = 0;
   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;
}
int main(){
   string s;
   s = ")))(((";
   cout << costToBalance(s) << endl;
   s = "))((";
   cout << costToBalance(s) << endl;
   return 0;
}

输出结果

9
4