[LeetCode]Evaluate Reverse Polish Notation

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值