이 튜토리얼에서는 괄호의 균형을 맞추는 비용을 찾는 프로그램에 대해 논의할 것입니다.
이를 위해 일련의 브래킷이 제공됩니다. 우리의 임무는 방정식에서 괄호의 위치를 1만큼 이동하여 균형을 맞추고 균형을 맞출 수 없는 경우 -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