-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression_validate.cpp
More file actions
72 lines (59 loc) · 2.07 KB
/
expression_validate.cpp
File metadata and controls
72 lines (59 loc) · 2.07 KB
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
#include <iostream>
#include <stack>
#include <string>
bool validate_brackets(std::string expression) {
std::stack<char> opening_brackets;
char top;
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == '[' || expression[i] == '{' || expression[i] == '(') {
opening_brackets.push(expression[i]);
continue;
}
if (expression[i] == ']' || expression[i] == '}' || expression[i] == ')') {
if (opening_brackets.empty())
return false;
switch (expression[i]) {
case ']' :
top = opening_brackets.top();
if (top == '{' || top == '(')
return false;
opening_brackets.pop();
break;
case '}' :
top = opening_brackets.top();
if (top == '[' || top == '(')
return false;
opening_brackets.pop();
break;
case ')' :
top = opening_brackets.top();
if (top == '{' || top == '[')
return false;
opening_brackets.pop();
break;
}
}
}
return(opening_brackets.empty());
}
bool validate_operators(std::string expression){
for (int i = 0; i < expression.length(); i++){
bool ex = (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/');
if (ex && i != 0) {
if (expression[i-1] == NULL || expression[i+1] == NULL)
return false;
}
}
return true;
}
int main()
{
std::string exp[] = {"((()))","(a+b)*c","(1+2*3/2*(9-5)","[4*(2+9)/3]","(()((())()))","[(])","[2+5-1*3(3+1)]"};
for (int i = 0; i < 7; i++ ){
if (validate_brackets(exp[i]) && validate_operators(exp[i]))
std::cout << exp[i] << " : Valid"<<std::endl;
else
std::cout << exp[i]<< " : Invalid"<<std::endl;
}
return 0;
}