平衡 C++ 中的括号的成本
在本教程中,我们将讨论一个程序来查找平衡括号的成本。
为此,我们将得到一系列括号。我们的任务是通过移动括号一个位置来平衡等式中的这些括号,如果无法平衡,则打印 -1。
示例
#include <bits/stdc++.h>
using namespace std;
int costToBalance(string s) {
if (s.length() == 0)
cout << 0 << endl;
//storing count of opening and
//closing parentheses
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP