Total Submission(s): 1354 Accepted Submission(s): 665
You’re given a non empty string made in its entirety from opening and closing braces. Your task is to find the minimum number of “operations” needed to make the string stable. The definition for being stable is as follows:
1. An empty string is stable.
2. If S is stable, then {S} is also stable.
3. If S and T are both stable, then ST (the concatenation of the two) is also stable.
All of these strings are stable: {}, {}{}, and {{}{}}; But none of these: }{, {{}{, nor {}{.
The only operation allowed on the string is to replace an opening brace with a closing brace, or visa-versa.
The last line of the input is made of one or more ’-’ (minus signs.)
k. N
Where k is the test case number (starting at one,) and N is the minimum number of operations needed to convert the given string into a balanced one.
Note: There is a blank space before N.
#include<iostream>
#include<string>
using namespace std;
int main(){
int i,j,k,l,t=1;
string s;
while(cin>>s&&s[0]!='-'){
j=0;
k=0;
l=s.length();
for(i=0;i<l;i++){
if(s[i]=='{')
j++;
else{
if(j!=0){
j--;
}
else{
k++;
j++;
}
}
}
k=k+j/2;
printf("%d. %d\n",t,k);
t++;
}
return 0;
}