leetcode 150 逆波兰表达式求值

618 阅读2分钟

昨天晚上做商汤的笔试题做的这一题,调了半天,就通过了33.33%,笔试结束在leetcode上一跑代码,发现了哪里考虑的不周全了。这一题的逻辑实际上很简单,就是申请一个栈,遇到数字就压栈,遇到加减乘除就从栈里取出两个数,进行运算,运算后的结果再压回栈中。

一、当时写的代码存在的问题:

最大的问题就是对字符串操作不熟悉,已有的方法不会用,自己造轮子。由于输入是一行以空格相隔的字符,我当时把输入直接一行getline到一个字符串里,然后直接传进逆波兰表达式的函数中,这样做导致的最直接的问题是我需要一个字符一个字符的判断是不是数字,是不是运算符,运算符还好说,数字的话,不仅要识别出是数字,还要完成数字字符到数字值的转换(一位数字,多位数字,负数[当时没考虑到负数的情况])。

下来之后发现字符串是可以直接转成int型的啊,负数也可以。。。用atoi()这个方法就行。。。所以只要输入时处理成一个个字符串就ok了。

二、atoi()的用法

使用atoi()需要包含头文件 #include<stdlib.h>

用法:string str = "123"; int num = atoi(str.c_str());

之所以用c_str()是为了和C语言兼任,C中没有string类型,所以需要用c_str()将C++中string类型的对象转成C中的字符串型。

三、代码

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <stack>
#include <stdlib.h>
using namespace std;

void evalRPN(vector<string>& str)
{
	stack <int> tmp;
	int len = str.size();
	for (int i = 0; i < len; i++)
	{
		if (str[i] == "+")
		{
			int num2 = tmp.top();
			tmp.pop();
			int num1 = tmp.top();
			tmp.pop();
			int sumTmp = num1 + num2;
			tmp.push(sumTmp);
		}
		else if (str[i] == "-")
		{
			int num2 = tmp.top();
			tmp.pop();
			int num1 = tmp.top();
			tmp.pop();
			int sumTmp = num1 - num2;
			tmp.push(sumTmp);
		}
		else if (str[i] == "*")
		{
			int num2 = tmp.top();
			tmp.pop();
			int num1 = tmp.top();
			tmp.pop();
			int sumTmp = num1 * num2;
			tmp.push(sumTmp);
		}
		else if (str[i] == "/")
		{
			int num2 = tmp.top();
			tmp.pop();
			int num1 = tmp.top();
			tmp.pop();
			int sumTmp = num1 / num2;
			tmp.push(sumTmp);
		}
		else
		{
			int num = atoi(str[i].c_str());
			tmp.push(num);
		}
	}

	int result = tmp.top();
	cout << result << endl;
	return;
}

int main()
{
	vector <string> str;
	string tmp;
	while (cin >> tmp)
		str.push_back(tmp);
	evalRPN(str);
	return 0;
}