逆波蘭表達式求值
求逆波蘭表達式的值。
在逆波蘭表達法中,其有效的運算符號包括 +
, -
, *
, /
。每個運算對象可以是整數,也可以是另一個逆波蘭計數表達。
您在真實的面試中是否遇到過這個題?
Yes
樣例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
說明
標籤 Expand 相關題目 Expand
Timer Expand
http://baike.baidu.com/link?url=Jw0OTA4SpB7K9bDawyuQqUSAmXRHrreharvkSbufvgiw4M1FVpwDOg8i4EwYa1Ruaw_3vBFvotPZuOfK6d3rqq
解題思路:
可以使用棧
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
// Write your code here
if(tokens==null||tokens.length==0)
return 0;
Stack<Integer> stack = new Stack<>();
for(String str:tokens){
if("+".equals(str)){
int a =stack.pop();
int b = stack.pop();
int c = b+a;
stack.add(c);
}else if("-".equals(str)){
int a =stack.pop();
int b = stack.pop();
int c = b-a;
stack.add(c);
}else if("*".equals(str)){
int a =stack.pop();
int b = stack.pop();
int c = b*a;
stack.add(c);
}else if("/".equals(str)){
int a =stack.pop();
int b = stack.pop();
int c = b/a;
stack.add(c);
}else{
stack.add(Integer.valueOf(str));
}
}
return stack.pop();
}
}