Update Paranthesis Matching.cpp

This commit is contained in:
Ashwek Swamy 2018-11-13 22:32:40 +05:30 committed by GitHub
parent 16e1bcdb52
commit ff41e4a60c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,52 +1,63 @@
#include<iostream> #include<iostream>
#include<stdlib.h>
#include<string> #include<string>
#include<stdio.h>
using namespace std; using namespace std;
const int MAX = 100; #define MAX 100
// -------------- stack -------------- // -------------- stack --------------
char stack[MAX]; char stack[MAX];
int top=0; int top = -1;
void push(char ch) void push(char ch){
{ stack[ ++top ] = ch;
stack[top++]=ch;
} }
char pop() char pop(){
{ return stack[ top-- ];
return stack[--top];
} }
// -------------- end stack ----------- // -------------- end stack -----------
int main() char opening(char ch){
{ switch(ch){
string exp; case '}':
cout<<"Enter The Expression : "; return '{';
cin >> exp; case ']':
for (int i = 0; i < exp.length(); i++) return '[';
{ case ')':
if (exp[i]=='(' || exp[i]=='{' || exp[i]=='[' || exp[i]=='<') return '(';
{ case '>':
push(exp[i]); return '<';
}
else if (exp[i]==')' || exp[i]=='}' || exp[i]==']' || exp[i]=='>')
{
pop();
} }
} }
// makes sure the stack is empty after processsing (above) int main(){
if(top==0)
{ string exp;
cout<<"Correct Expression"; int valid = 1, i = 0;
cout<<"Enter The Expression : ";
cin >> exp;
while (valid == 1 && i < exp.length()){
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){
push(exp[i]);
} }
else else if (top >= 0 && stack[top] == opening(exp[i])){
{ pop();
}
else{
valid = 0;
}
i++;
}
// makes sure the stack is empty after processsing (above)
if (valid == 1 && top == -1){
cout<<"\nCorrect Expression";
}
else{
cout<<"\nWrong Expression"; cout<<"\nWrong Expression";
} }