您的位置:首页 > 编程语言 > Lua

Evaluate Reverse Polish Notation【leetcode 2】

2014-09-15 19:02 363 查看
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. atoi函数:把字符串转换成整型数。ASCII to integer 的缩写。

原型:

int atoi(const char *nptr);

参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零。

头文件: #include <stdlib.h>

2. c_str()函数

string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

3.考虑压栈的顺序,如a/b和a-b操作,先弹出的是b,后弹出的是a ,注意顺序

代码:

#include <iostream>
#include <cstring>
#include <vector.h>
#include <stack.h>
using namespace std;

//["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
//["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

int evalRPN(vector<string> & tokens ){

	stack<int> op;
	int s = tokens.size();
	//vector<string>::iterator iter = tokens.begin();//迭代器
	int a ,b;
	for(int i=0;i<s;i++){
		if(tokens[i] == "+"){
			a = op.top();
			op.pop();
			b = op.top();
			op.pop();
			op.push(a+b);
		}else //之前没有这个else就有问题
		if(tokens[i] == "-"){
			a = op.top();
			op.pop();
			b = op.top();
			op.pop();
			op.push(b-a);
		}else//之前没有这个else就有问题
		if(tokens[i] == "*"){
			a = op.top();
			op.pop();
			b = op.top();
			op.pop();
			op.push(a*b);
		}else//之前没有这个else就有问题
		if(tokens[i] == "/"){
			a = op.top();
			op.pop();
			b = op.top();
			op.pop();
			op.push(b/a);  //different
		}
		else
		{//  is a number
			op.push(atoi(tokens[i].c_str()));
			//这里之前用迭代器做,就这个位置中出错
			//op.push(atoi(*iter.c_str())); //error
		}
	}
	return op.top();

    }

int main() {
	vector<string> s ;
	s.push_back("2");
	s.push_back("1");
	s.push_back("+");
	s.push_back("3");
	s.push_back("*");

	cout<<evalRPN(s);
	return 0;
}


输出: 9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: