LeetCode OJ:Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

  Total Accepted: 3892  Total Submissions: 20348 My Submissions

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

算法思想:栈操作,逆波兰表达式:

# include <stack>
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> val;
		for(int i=0;i<tokens.size();i++){
			if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/"){
				val.push(atoi(tokens[i].c_str()));
				continue;
			}
			int a=val.top();val.pop();
			int b=val.top();val.pop();
			switch(tokens[i][0]){
			case '+':
				val.push(a+b);break;
			case '-':
				val.push(b-a);break;
			case '*':
				val.push(a*b);break;
			case '/':
				val.push(b/a);break;
			}
		}
		return val.top();
    }
};

递归版

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        int x,y;
        auto token=tokens.back();
        tokens.pop_back();
        if(token=="+"||token=="-"||token=="*"||token=="/"){
            y=evalRPN(tokens);
            x=evalRPN(tokens);
        }
        if(token=="+")x+=y;
        else if(token=="-")x-=y;
        else if(token=="*")x*=y;
        else if(token=="/")x/=y;
        else x=stoi(token);
        return x;
    }
};


你可能感兴趣的:(LeetCode,栈)