根据逆波兰式(后序遍历),计算出相应的结果,,
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
class Solution {
public:
int evalRPN(vector<string> &tokens) {
int n = tokens.size();
if(n<=0)return 0;
int temp;
stack<int> stk;
int l,r;
for(int i=0;i < n; i ++){
if(!(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") ){
stk.push(str_to_int(tokens[i]));
}
else{
r = stk.top(); stk.pop();
l = stk.top();stk.pop();
if(tokens[i] == "+"){
stk.push(r+l);
}
else if(tokens[i] == "-")stk.push(l-r);
else if(tokens[i] == "*")stk.push(l*r);
else if(tokens[i] == "/"){
if(r != 0)stk.push(l/r);
else{
return 0;
}
}
}
}
return stk.top();
}
int str_to_int(string s){//字符串转化相应的整型数字,
if(s.length() <= 0)return 0;
int result = 0;
int flag = 1;
if(s[0] == '+' || s[0] == '-'){
if(s[0] == '-')flag=-1;
for(int i = 1; i < s.length();i++){
result = result*10+s[i]-'0';//注意很上面函数中vector<string>的区别,,字符串string s;对应的为字符数组,,
}
}
else{
for(int i = 0;i < s.length(); i++){
result =result*10+s[i]-'0';
}
}
return result*flag ;
}
};
Java
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0;i<tokens.length;i++){
try{
int num = Integer.parseInt(tokens[i]);
stack.add(num);
}catch (Exception e) {
int b = stack.pop();
int a = stack.pop();
stack.add(get(a, b, tokens[i]));
}
}
return stack.pop();
}
private int get(int a,int b,String operator){
switch (operator) {
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
}