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
本题是关于逆波兰式的求取结果问题,很明显栈是最简单的,懂逆波兰的过程就可以了。
这里遇到的问题:
1.对C++不熟,不知道怎么判断string是否为num的Function,于是自己写了一个,凑合着用了;
2.开始准备连string to int都自己写了,后来发现了两个解决方案:一个是用C++ string类里的c_str()方法把string变成字符串,那样直接可以用atoi了;
一个是用stoi(),这后来才发现的,非常省事的功能,效率也肯定要高。
3.还有就是iterartor的使用,一直写C,发现C++和C还是有非常大的不一样的,得把思路转一转,iterator作为一种泛型指针还得常用的,毕竟C++中最重要的就是重用,而起根基之一就是泛型!
参考:http://blog.csdn.net/doc_sgl/article/details/17101519
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
bool isNum(string &s)
{
if ((s.at(0) == '+' && s.length() != 1) ||
(s.at(0) == '-' && s.length() != 1) ||
(s.at(0) >= '0' && s.at(0) <= '9'))
{
for (int i = 1; i < s.length(); i++)
{
if (!(s.at(i) >= '0' && s.at(i) <= '9'))
{
return false;
}
}
return true;
}
return false;
}
int evalRPN(vector<string> &tokens) {
vector<string>::iterator it = tokens.begin();
stack<int> res;
while (it != tokens.end())
{
if (isNum(*it))
{
res.push(stoi(*it));
}
else
{
int t1, t2;
t2 = res.top(); res.pop();
t1 = res.top(); res.pop();
if (*it == "+")
res.push(t1 + t2);
else if (*it == "-")
res.push(t1 - t2);
else if (*it == "*")
res.push(t1 * t2);
else if (*it == "/")
res.push(t1 / t2);
}
it++;
}
return res.top();
}
};
int main()
{
vector<string> a = { "0", "3", "/" };
Solution aa;
cout << aa.evalRPN(a) << endl;
system("PAUSE");
return 0;
}