Code for expression evaluation ( ( 1 + 3 ) / ( sqrt 9 ) )
//time: O(N), space: O(N)
import java.util.Stack;
import java.lang.Math;
public class Evaluate {
public static void main(String...args) {
Stack<String> ops = new Stack<>();
Stack<Double> vals = new Stack<>();
String expr = "( ( 1 + 3 ) / ( sqrt 9 ) )";
for(int s : expr.split(" ")) {
if(s.equals("(")) {//do nothing}
else if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("sqrt")) ops.push(s);
else if(s.equals(")")) {
String op = ops.pop();
double v = vals.pop();
if(op.equals("+")) v += vals.pop();
else if(op.equals("-")) v -= vals.pop();
else if(op.equals("*")) v *= vals.pop();
else if(op.equals("/")) v /= vals.pop();
else if(op.equals("sqrt") v = Math.sqrt(v);
push(v);
}
else vals.push(Double.parseDouble(s));
}
Double result = vals.pop();
}
}
//time: O(N), space: O(N)
import java.util.Stack;
import java.lang.Math;
public class Evaluate {
public static void main(String...args) {
Stack<String> ops = new Stack<>();
Stack<Double> vals = new Stack<>();
String expr = "( ( 1 + 3 ) / ( sqrt 9 ) )";
for(int s : expr.split(" ")) {
if(s.equals("(")) {//do nothing}
else if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("sqrt")) ops.push(s);
else if(s.equals(")")) {
String op = ops.pop();
double v = vals.pop();
if(op.equals("+")) v += vals.pop();
else if(op.equals("-")) v -= vals.pop();
else if(op.equals("*")) v *= vals.pop();
else if(op.equals("/")) v /= vals.pop();
else if(op.equals("sqrt") v = Math.sqrt(v);
push(v);
}
else vals.push(Double.parseDouble(s));
}
Double result = vals.pop();
}
}