-
Notifications
You must be signed in to change notification settings - Fork 106
/
Parenthesis_Validity.cpp
88 lines (77 loc) · 2.07 KB
/
Parenthesis_Validity.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <cstring>
#include "../Stack/include/Stack.h"
using namespace std;
bool IsValid (char expression[])
{
int n = strlen(expression);
Stack<char> stackChar = Stack<char>();
for (int i = 0; i < n; ++i)
{
// If input is opened parenthesis
// just store it in the stack
if(expression[i] == '{')
{
stackChar.Push('{');
}
else if(expression[i] == '[')
{
stackChar.Push('[');
}
else if(expression[i] == '(')
{
stackChar.Push('(');
}
// Check when the input
// is closed parenthesis
else if (
expression[i] == '}' ||
expression[i] == ']' ||
expression[i] == ')')
{
// If the stack is empty
// or the last parenthesis is different
// than the one we are closed,
// then the expression is wrong
if(expression[i] == '}' &&
(stackChar.IsEmpty() || stackChar.Top() != '{'))
return false;
else if(expression[i] == ']' &&
(stackChar.IsEmpty() || stackChar.Top() != '['))
return false;
else if(expression[i] == ')' &&
(stackChar.IsEmpty() || stackChar.Top() != '('))
return false;
else
stackChar.Pop();
}
}
// If the stack is empty,
// the expression is valid
// otherwise it's invalid
if (stackChar.IsEmpty())
return true; //
else
return false;
}
int main()
{
// Prepare array for storing
// the expression
char expr[1000];
// Ask user to input the expression
cout << "Please type the parenthesis expression ";
cout << "then press ENTER!" << endl;
cin >> expr;
// Check the validity
bool bo = IsValid(expr);
// Notify the user
cout << endl;
cout << "The " << expr << " expression is ";
if(bo)
cout << "valid";
else
cout << "invalid";
cout << endl;
return 0;
}