LeetCode—Evaluate Reverse Polish Notation 逆波兰写法的解析

Evaluate Reverse Polish Notation

  Total Accepted: 22394  Total Submissions: 112626 My Submissions

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

这是一个逆波兰写法的解析,题目比较简单:
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
	int evalRPN(vector<string> &tokens) {
		vector<string> :: size_type size = tokens.size();
		vector<int> value;
		int valueCurrentSize = 0;
		int tempvalue = 0;
		int i = 0;
		while(i < size)
		{
			if(tokens[i] == "+")
			{
				if(value.size() < 2)
				{
					return 0;
				}
				tempvalue = value[valueCurrentSize-2]+value[valueCurrentSize-1];
				value.pop_back();
				value[valueCurrentSize-2] = tempvalue;
				valueCurrentSize--;
			}
			else if(tokens[i] == "-")
			{
				if(value.size() < 2)
				{
					return 0;
				}
				tempvalue = value[valueCurrentSize-2]-value[valueCurrentSize-1];
				value.pop_back();
				value[valueCurrentSize-2] = tempvalue;
				valueCurrentSize--;
			}
			else if(tokens[i] == "*")
			{
				if(value.size() < 2)
				{
					return 0;
				}
				tempvalue = value[valueCurrentSize-2]*value[valueCurrentSize-1];
				value.pop_back();
				value[valueCurrentSize-2] = tempvalue;
				valueCurrentSize--;
			}
			else if(tokens[i] == "/")
			{
				if(value.size() < 2)
				{
					return 0;
				}
				tempvalue = value[valueCurrentSize-2]/value[valueCurrentSize-1];
				value.pop_back();
				value[valueCurrentSize-2] = tempvalue;
				valueCurrentSize--;
			}
			else
			{
				value.push_back(atoi(tokens[i].c_str()));
				valueCurrentSize++;
			}
			i++;
		}
		return  value[0];

	}
};
void main()
{
	vector<string> tokens;
	tokens.push_back("2");
	tokens.push_back("1");
	tokens.push_back("+");
	tokens.push_back("3");
	tokens.push_back("*");
	Solution rt;
	int value = rt.evalRPN(tokens);

}

解答过程中用了vector容器来存放结果,但是vector在取最后一个元素的时候使用索引进行取值,相当不方便
因此这里的存储结构应该换成stack栈,取栈顶元素,直接选用top()函数就可以了

同时写的时候有个疑问就是string类中如果取单个元素会是什么情况,写程序验证一下:
#include <string>
#include <iostream>
using namespace std;
void main()
{
	string val = "xie+1990+ting";
	char x = val[0];
	char y = val[4];
	int  z = val[4]-'0';
	cout << x << " " << z;
}
输出为x,1
所以string字符串取单个字符是char类型

你可能感兴趣的:(LeetCode,逆波兰)