试解leetcode算法题--逆波兰表达式求值

本文介绍了一种解决逆波兰表达式求值问题的方法,使用C++实现了一个算法,能够处理包括加、减、乘、除在内的运算。文章提供了详细的代码实现,并解释了算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<题目表述>

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。给定表达式总是有效的。

示例 1:

输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9

<原题链接>

https://leetcode-cn.com/problems/evaluate-reverse-polish-notation

<思路>

该题按照逆波兰的算法规则书写代码即可通过。

【注】关于如何将一个中序表达式转换为逆波兰形式详见我的另一篇博客。

<样例代码>

#include<iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;
class Solution {
private:
	int toInt(string str);
	int exec(int a, int b, char ch);
public:
	int evalRPN(vector<string>& tokens) {
		stack<int>  num;
		for (int i = 0; i < tokens.size(); i++)
		{
			if ((tokens[i][0] >= '0' && tokens[i][0] <= '9') ||
				(tokens[i][0] == '-' && tokens[i][1] >= '0' && tokens[i][1] <= '9'))
				num.push(toInt(tokens[i]));
			else
			{
				int a = num.top(); num.pop();
				int b = num.top(); num.pop();
				num.push(exec(b, a, tokens[i][0]));
			}
		}
		return num.top();
	}
};

int Solution::toInt(string str)
{
	int ans = 0, i = 0;
	bool flag = false;
	if (str[0] == '-')
	{
		i = 1;
		flag = true;
	}
	for (; i < str.length(); i++)
		ans = ans * 10 + (str[i] - 48);
	if (flag)
		return -ans;
	return ans;
}

int Solution::exec(int a, int b, char ch)
{
	switch (ch)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a * b;
	case '/':
		return a / b;
	default:
		break;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值