用栈实现比较简单,遇到数字压栈,遇到运算符号两次出栈运算,再将结果压栈,遍历一次vector即可。
注意:将字符串转为int时,使用atoi可以accept,但用自己编写的转换函数会超时。
//2014年8月20日20:35:12
//2014年8月20日21:08:26
#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for(vector<string>::size_type i=0 ; i<tokens.size() ; i++){
if(tokens[i] == "+"){
int b = st.top();
st.pop();
int a = st.top();
st.pop();
st.push(a + b);
}
else if(tokens[i] == "-"){
int b = st.top();
st.pop();
int a = st.top();
st.pop();
st.push(a - b);
}
else if(tokens[i] == "*"){
int b = st.top();
st.pop();
int a = st.top();
st.pop();
st.push(a * b);
}
else if(tokens[i] == "/"){
int b = st.top();
st.pop();
int a = st.top();
st.pop();
st.push(a / b);
}
else {
// int a = myStringToInt(tokens[i]);
int a = atoi((tokens[i]).c_str());;
// cout << tokens[i] << " " << a << endl;
st.push(a);
}
}
return st.top();
}
int myStringToInt(string &s)
{
if(s == ""){
return 0;
}
int ret = 1;
bool IsPositive = false;
// cout << s << endl;
if(s[0] == '-'){
IsPositive = true;
}
else{
ret = ret * (int)(s[0] - '0');
}
for(string::size_type i=1 ; i<s.length() ; i++){
ret *= 10;
ret += (int)(s[i] - '0');
}
if(IsPositive == true){
return 0 - ret;
}
else{
return ret;
}
}
};
int main()
{
vector<string> tokens;
// tokens.push_back("2");
// tokens.push_back("1");
// tokens.push_back("+");
// tokens.push_back("3");
// tokens.push_back("*");
tokens.push_back("4");
tokens.push_back("13");
tokens.push_back("5");
tokens.push_back("/");
tokens.push_back("+");
Solution A;
cout << A.evalRPN(tokens) << endl;
return 0;
}