-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidExpression.java
More file actions
106 lines (96 loc) · 2.82 KB
/
validExpression.java
File metadata and controls
106 lines (96 loc) · 2.82 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.Stack;
/**
* Write a description of class validExpression here.
*
* @author (Kelvin Likollari)
* @version (04.06.2021)
*/
public class validExpression
{
/**
* @param args the command line arguments
*/
static boolean checkValid(char[] equ){
int i,j = equ.length;
Stack<Character> astack = new Stack<>();
if (j==0) {
return false;
}
for(i=0; i<j; i++){
// System.out.println("?"+equ[i]);
if (isOpen(equ[i])){
if (!astack.isEmpty() && isNumber(astack.peek())) {
return false;
}
astack.push(equ[i]);
} else if (isNumber(equ[i])){
astack.push(equ[i]);
} else if (isOp(equ[i])){
if (astack.isEmpty() || !isNumber(astack.peek())) {
return false;
}
astack.push(equ[i]);
} else if (isClose(equ[i])){
if (astack.isEmpty() || !isNumber(astack.peek())) {
return false;
}
while(!astack.isEmpty()){
char temp=astack.pop();
if (isOpen(temp)) {
if (doMatch(temp,equ[i])) {
break;
} else {
return false;//unexpected open
}
} else {
if(astack.isEmpty()) {
return false;
}
}
}
astack.push('1');
} else { //unexpected char
return false;
}
}
if (!astack.isEmpty() && !isNumber(astack.peek())) {
return false;
}
while (!astack.isEmpty()) {
if(isOpen(astack.pop())) {
return false;
}
}
return true;
}
private static boolean isOpen(char c) {
if(c == '(' || c== '[' ) {
return true;
}
return false;
}
private static boolean isNumber(char c) {
if((c >= '0' && c <= '9' ) || (c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z' )) {
return true;
}
return false;
}
private static boolean isOp(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return true;
}
return false;
}
private static boolean isClose(char c) {
if(c == ')' || c == ']') {
return true;
}
return false;
}
private static boolean doMatch(char temp, char c) {
if((temp == '(' && c == ')')||(temp == '[' && c == ']')) {
return true;
}
return false;
}
}