C++ Solution using std::stack solution


  • 0
    J

    Use stack to store operand, and when meet operator, pop out two operands to compute, and then push the result into stack

    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
           	/*
    			扫描字符串,数字转换后入栈,遇到符号出栈两个数字计算后再入栈
    			scan tokens, if digit then push it into stack, 
    			if operator then two digits pop from stack, make computation and push the result into stack
           	*/
    		stack<int> sdata;
    		for(int i = 0; i < tokens.size(); i ++){
    			if( (tokens[i] == "+") ||
    				(tokens[i] == "-") ||
    				(tokens[i] == "*") ||
    				(tokens[i] == "/")){
    					int x = sdata.top();
    					sdata.pop();
    					int y = sdata.top();
    					sdata.pop();
    					int z;
    					if(tokens[i] == "+") z = y + x;
    					if(tokens[i] == "-") z = y - x;
    					if(tokens[i] == "*") z = y * x;
    					if(tokens[i] == "/") z = y / x;
    					sdata.push(z);
    				}
    			else{
    				// int tmpdata = atoi(tokens[i].c_str());
    				int tmpdata = stoi(tokens[i]);
    				sdata.push(tmpdata);
    			}
    		}
    		int res = sdata.top();
    		return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.