题目描述:
解题思路:
利用栈去模拟后缀表达式
参考代码:
public long solve (String str) {
// write code here
Stack<Long> s = new Stack<>();
long temp = 0;
for(int i =0; i<str.length(); i++){
if(str.charAt(i)>='0' && str.charAt(i)<='9'){
temp*=10;
temp+=str.charAt(i)-'0';
}else if(str.charAt(i)=='#'){
s.push(temp);
temp = 0;
}else{
long p1 = s.pop();
long p2 = s.pop();
switch (str.charAt(i)){
case '+': s.push(p1+p2);break;
case '-': s.push(p2-p1);break;
case '*': s.push(p1*p2);break;
}
}
}
return s.peek();
}