C.牛牛与后缀表达式-JAVA版
用一个栈维护即可,遇到#就把前面的数扔进去,遇到运算符就弹出来两个进行运算,运算之后再扔进去,一个for循环之后栈中只有一个结果即答案,弹出即可
public long solve (String str) {
// write code here
long n=0;
Stack<Long> stack = new Stack();
for(int i=0;i<str.length();i++) {
if (str.charAt(i)>='0' && str.charAt(i)<='9') {
n=n*10+(str.charAt(i)-'0');//计算#之前的数
}
else if (str.charAt(i)=='#') {
stack.push(n);
n=0;扔进栈之后,将数归0,为了重新计算下一个数
}
else {
long b = stack.pop(); //根据stack的特性,弹出来的第一个即是b
long a = stack.pop();
if (str.charAt(i)=='-') {
stack.push(a-b);
}
else if(str.charAt(i)=='+') {
stack.push(a+b);
}
else {
stack.push(a*b);
}
}
}
return stack.pop();
} 
京公网安备 11010502036488号