-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArithmetic Expressions .java
56 lines (44 loc) · 1.16 KB
/
Arithmetic Expressions .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
//Arithmetic Expressions
/* Evaluate Postfix Expression Using Stack
example :
input : (a+b)*(c-d) output: ab+cd-*
*/
static MyStack <String > st= new MyStack<>();static String ans="";
public static int findPrec(String s){
int prec=0;
switch (s) {
case "-":
case "+": prec = 1; break;
case "*":
case "/": prec = 2; break;
}
return prec;
}
public static void arithmiticExpresionH(String s,int prec) {
if(!st.isEmpty()) {
if (prec <= findPrec(st.peak()))
ans += st.pop();
}
st.push(s);
}
public static String arithmiticExpresion(String s){
String ch;
for(int i=0;i<s.length();i++){
ch=s.charAt(i)+"";
switch(ch){
case "+":
case "-":arithmiticExpresionH(ch,1);break;
case "*":
case "/":arithmiticExpresionH(ch,2); break;
case "(": st.push(ch);break;
case ")":{
while(!st.peak().equals("(")){
ans+=st.pop();
}st.pop();
}break;
default : ans+=ch;
}
}
while(!st.isEmpty())ans+=st.pop();
return ans;
}