Algorithm
Parenthesis Balance I
By Neilor Tonin, URI Brazil
Considering an expression with parenthesis, print a message informing if the among of parenthesis is correct or incorrect, without considering the rest of the expression. Example:
a+(b*c)-2-a is correct(a+b*(2-c)-2+a)*2 is correct
when
(a*b-(2+c) is incorrect
2*(3-a)) is incorrect
)3+b*(2-c)( is incorrect
Resuming, all closing parenthesis must have an open parenthesis and it's not possible a closing parenthesis without a previous open parenthesis, and the quantity of closing and open parenthesis must be the same.
Input
The input file contains N expressions (1 <= N <= 10000), each one with up to 1000 characters.
Output
The output must be correct or incorrect for each test case according with above rules.
Input Sample | Output Sample |
a+(b*c)-2-a |
correct correct incorrect incorrect incorrect |
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main() {
int size;
string line;
while(getline(cin, line)) {
size = line.length();
stack < char> s;
for (int i = 0; i < size; ++i) {
if(line[i] == '(')
s.push(i);
if(line[i] == ')') {
if(!s.empty()) {
s.pop();
} else {
s.push(i);
}
}
}
if(s.empty())n{
cout << "correct" << endl;
} else {
cout << "incorrect" << endl;
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output