-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuilder.java
100 lines (93 loc) · 3.21 KB
/
Builder.java
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
import java.util.Stack;
/**
* Created by lsr on 2016/11/30.
*/
public class Builder {
public static ExTreeNode generate(String input){
Stack<String> operator = new Stack<>();
Stack<ExTreeNode> opobejct= new Stack<>();
input = input.replaceAll("\\({1}","( ");
input = input.replaceAll("\\){1}"," )");
input = input.replaceAll("\\s{1,}"," ");
String[] words=input.split(" ");
replace_key(words);
for(int i=0;i<words.length;i++){
words[i] = words[i].trim();
char op = words[i].charAt(0);
switch (op){
case '+':
case '-':
case '*':
case '/':
case '&':
case '|':
case '=':
case '>':
case '<':
// operation handle;
// judge priority
int cur_priority = priority(words[i]);
while(!operator.isEmpty()&&cur_priority<priority(operator.peek())){
ExTreeNode right = opobejct.pop();
ExTreeNode left = opobejct.pop();
String op1 = operator.pop();
opobejct.push(new ExTreeNode(left,right,op1));
}
operator.push(words[i]);
break;
case '(':
operator.push(words[i]);
break;
case ')':
while(!operator.isEmpty()&& !operator.peek().equalsIgnoreCase("(")){
ExTreeNode right = opobejct.pop();
ExTreeNode left = opobejct.pop();
String op1 = operator.pop();
opobejct.push(new ExTreeNode(left,right,op1));
}
if(operator.peek()==null||!operator.peek().equalsIgnoreCase("(")){
System.out.print("wrong input");
return null;
}
operator.pop();
break;
default:
opobejct.push(new ExTreeNode(words[i]));
}
}
while(!operator.isEmpty()){
ExTreeNode right = opobejct.pop();
ExTreeNode left = opobejct.pop();
String op1 = operator.pop();
opobejct.push(new ExTreeNode(left,right,op1));
}
return opobejct.pop();
}
private static void replace_key(String[] words) {
for(int i=0;i<words.length;i++){
if(words[i].equalsIgnoreCase("and")){
words[i] = "&";
continue;
}
if(words[i].equalsIgnoreCase("or")){
words[i] = "|";
continue;
}
}
}
private static int priority(String word){
char op = word.charAt(0);
switch (op){
case '|': return 0;
case '&': return 1;
case '>':
case '<':
case '=': return 2;
case '+':
case '-': return 3;
case '*':
case '/': return 4;
default: return -1;
}
}
}