每日kata~05-Reverse-polish-notatio
2020-04-29 本文已影响0人
Lacia
逆波兰表达式
Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
For example expression 5 1 2 + 4 * + 3 -
(which is equivalent to 5 + ((1 + 2) * 4) - 3
in normal notation) should evaluate to 14
.
Note that for simplicity you may assume that there are always spaces between numbers and operations, e.g. 1 3 +
expression is valid, but 1 3+
isn't.
Empty expression should evaluate to 0
.
Valid operations are +
, -
, *
, /
.
You may assume that there won't be exceptional situations (like stack underflow or division by zero).
Solution
正则&栈
第一次做的时候没判断栈为空的情况,加入判断之后√
做计算处理的时候有些麻烦了,用了最笨的方法(:з」∠)
public static double evaluate(String expr) {
// TODO: Your awesome code here
if(expr=="") {
return 0;
}
String[] w = expr.split("\\s+");
int l = w.length;
double c = 0;
Stack<String> st = new Stack<String>();
for(int i=0;i<l;i++) {
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
Matcher isNum = pattern.matcher(w[i]);
if(isNum.matches()) {
st.push(w[i]);
}
else {
double a = Double.parseDouble(st.pop());
double b = Double.parseDouble(st.peek());
if(!st.empty()) {
st.pop();
}
if((w[i].toCharArray())[0]=='+') {
c = b + a;
}
if((w[i].toCharArray())[0]=='-') {
c = b - a;
}
if((w[i].toCharArray())[0]=='*') {
c = b * a;
}
if((w[i].toCharArray())[0]=='/') {
c = b / a;
}
st.push(String.valueOf(c));
}
}
return Double.parseDouble(st.peek());
}