标签:io os for sp c on amp r size
初看貌似有点复杂,但是搞懂了非常简单,就一个简单的栈应用,每次遇到计算符号"+", "-", "*", "/"就将栈顶端两个数字出栈,计算后再将结果压栈即可。。
#include<iostream> #include<vector> #include<stack> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> stack; for (int i = 0; i < tokens.size(); i++) { if (tokens[i] == "*" || tokens[i] == "-" || tokens[i] == "+" || tokens[i] == "/") { int val2 = stack.top(); stack.pop(); int val1 = stack.top(); stack.pop(); int tmpVal; if (tokens[i] == "*") tmpVal = val1 * val2; else if (tokens[i] == "-") tmpVal = val1 - val2; else if (tokens[i] == "+") tmpVal = val1 + val2; else tmpVal = val1 / val2; stack.push(tmpVal); } else { int tmpVal = atoi(tokens[i].c_str()); stack.push(tmpVal); } } return stack.top(); } };
Leetcode - Evaluate Reverse Polish Notation
标签:io os for sp c on amp r size
原文地址:http://blog.csdn.net/tspatial_thunder/article/details/39755011