mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Update Paranthesis Matching.cpp
This commit is contained in:
parent
16e1bcdb52
commit
ff41e4a60c
@ -1,52 +1,63 @@
|
||||
#include<iostream>
|
||||
#include<stdlib.h>
|
||||
#include<string>
|
||||
#include<stdio.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
const int MAX = 100;
|
||||
#define MAX 100
|
||||
|
||||
// -------------- stack --------------
|
||||
|
||||
char stack[MAX];
|
||||
int top=0;
|
||||
int top = -1;
|
||||
|
||||
void push(char ch)
|
||||
{
|
||||
stack[top++]=ch;
|
||||
void push(char ch){
|
||||
stack[ ++top ] = ch;
|
||||
}
|
||||
|
||||
char pop()
|
||||
{
|
||||
return stack[--top];
|
||||
char pop(){
|
||||
return stack[ top-- ];
|
||||
}
|
||||
|
||||
// -------------- end stack -----------
|
||||
|
||||
int main()
|
||||
{
|
||||
string exp;
|
||||
cout<<"Enter The Expression : ";
|
||||
cin >> exp;
|
||||
for (int i = 0; i < exp.length(); i++)
|
||||
{
|
||||
if (exp[i]=='(' || exp[i]=='{' || exp[i]=='[' || exp[i]=='<')
|
||||
{
|
||||
push(exp[i]);
|
||||
}
|
||||
else if (exp[i]==')' || exp[i]=='}' || exp[i]==']' || exp[i]=='>')
|
||||
{
|
||||
pop();
|
||||
char opening(char ch){
|
||||
switch(ch){
|
||||
case '}':
|
||||
return '{';
|
||||
case ']':
|
||||
return '[';
|
||||
case ')':
|
||||
return '(';
|
||||
case '>':
|
||||
return '<';
|
||||
}
|
||||
}
|
||||
|
||||
// makes sure the stack is empty after processsing (above)
|
||||
if(top==0)
|
||||
{
|
||||
cout<<"Correct Expression";
|
||||
int main(){
|
||||
|
||||
string exp;
|
||||
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";
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user