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

77 lines
959 B
C++
Raw Normal View History

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