TheAlgorithms-C-Plus-Plus/Others/Paranthesis Matching.cpp

66 lines
957 B
C++
Raw Normal View History

2017-12-24 01:30:49 +08:00
#include<iostream>
2018-03-28 04:51:40 +08:00
#include<string>
2018-11-14 01:02:40 +08:00
2017-12-24 01:30:49 +08:00
using namespace std;
2018-11-14 01:02:40 +08:00
#define MAX 100
2018-03-28 04:51:40 +08:00
// -------------- stack --------------
char stack[MAX];
2018-11-14 01:02:40 +08:00
int top = -1;
2017-12-24 01:30:49 +08:00
2018-11-14 01:02:40 +08:00
void push(char ch){
stack[ ++top ] = ch;
2017-12-24 01:30:49 +08:00
}
2018-11-14 01:02:40 +08:00
char pop(){
return stack[ top-- ];
2017-12-24 01:30:49 +08:00
}
2018-03-28 04:51:40 +08:00
// -------------- end stack -----------
2017-12-24 01:30:49 +08:00
2018-11-14 01:02:40 +08:00
char opening(char ch){
switch(ch){
case '}':
return '{';
case ']':
return '[';
case ')':
return '(';
case '>':
return '<';
}
}
int main(){
2018-03-28 04:51:40 +08:00
string exp;
2018-11-14 01:02:40 +08:00
int valid = 1, i = 0;
2017-12-24 01:30:49 +08:00
cout<<"Enter The Expression : ";
2018-03-28 04:51:40 +08:00
cin >> exp;
2018-11-14 01:02:40 +08:00
while (valid == 1 && i < exp.length()){
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){
2017-12-24 01:30:49 +08:00
push(exp[i]);
}
2018-11-14 01:02:40 +08:00
else if (top >= 0 && stack[top] == opening(exp[i])){
pop();
}
else{
valid = 0;
2017-12-24 01:30:49 +08:00
}
2018-11-14 01:02:40 +08:00
i++;
2017-12-24 01:30:49 +08:00
}
2018-03-28 04:51:40 +08:00
// makes sure the stack is empty after processsing (above)
2018-11-14 01:02:40 +08:00
if (valid == 1 && top == -1){
cout<<"\nCorrect Expression";
2017-12-24 01:30:49 +08:00
}
2018-11-14 01:02:40 +08:00
else{
2017-12-24 01:30:49 +08:00
cout<<"\nWrong Expression";
}
2018-03-28 04:51:40 +08:00
2017-12-24 01:30:49 +08:00
return 0;
}