-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparenthesis.cpp
46 lines (39 loc) · 1.17 KB
/
parenthesis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* Balance checking for parenthesis */
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int main()
{
stack<char> parenthesis;
string expression;
cout<<"Enter expression :"<<endl;
getline(cin, expression); //Getting a line upto new line including space
for(int i = 0; expression[i] != 0; i++)
{
//Only checking for parenthesis and not square bracket or any other characters
if(expression[i] == '(' || expression[i] == ')')
{
if(parenthesis.size() == 0) //if stack empty push
{
parenthesis.push(expression[i]);
}
else{
//top() used to get the value in the stack
if(parenthesis.top() == '(' && expression[i] == ')')
{
parenthesis.pop(); //removes the top value from stack
}
else{
parenthesis.push(expression[i]); //or push it
}
}
}
}
//Novice Solution acquired ;-P
if(parenthesis.size() == 0)
cout<<"Valid";
else
cout<<"Invalid";
return 0;
}