字节一面手撕:带有括号的逆波兰表达式(结果输出是等式)

//通过分析我们找到哪种情况下括号是不能省略的:
//'+'对右边的'-'运算不能省略,
//'-'对右边的'+'和'-'运算,
//'*'对左边的'+'和'-'运算、对右边的'/''+''-'运算,
//'/'对左边的'+'和'-'以及对右边的所有运算不能省略 #include <iostream>
#include <sstream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;

stack<string> sta;
stack<char> myuse;
bool is_numoruse(char c) {
	if (c == '+' || c == '-' || c == '*' || c == '/') return false;
	else return true;
}
void solution(string &s) {
	for (int i = 0; i < s.size(); ++i) {
		if (is_numoruse(s[i])) {
			sta.push(s.substr(i, 1));
			myuse.push('#');
		}
		else {
			string tem = sta.top();
			sta.pop();
			char tem_c = myuse.top();
			myuse.pop();
			if (s[i] == '+') {
				if (tem_c == '-') {
					tem = '(' + tem + ')';
				}
			}
			else if (s[i] == '-') {
				if (tem_c == '+' || tem_c == '-') {
					tem = '(' + tem + ')';
				}
			}
			else if (s[i] == '*') {
				if (tem_c != '*'&&tem_c != '#') {
					tem = '(' + tem + ')';
				}
				if (myuse.top() == '+' || myuse.top() == '-') {
					sta.top() = '(' + sta.top() + ')';
				}
			}
			else {
				if (tem_c != '#') {
					tem = '(' + tem + ')';
				}
				if (myuse.top() == '+' || myuse.top() == '-') {
					sta.top() = '(' + sta.top() + ')';
				}
			}
			sta.top() += s[i] + tem;
			myuse.pop();
			myuse.push(s[i]);
		}
	}
}
int main() {
	string s = "ab*cd+*efgh/*//";
	solution(s);
	cout << sta.top() << endl;
	return 0;
}

全部评论
请问投的什么部门呢,使用牛客网面试的吗
点赞 回复 分享
发布于 2022-07-18 00:35

相关推荐

昨天 12:14
门头沟学院 Java
程序员小白条:oppo不用想了,经常看92都挂的
点赞 评论 收藏
分享
06-10 18:55
已编辑
西安电子科技大学 Java
只管努力就好:恭喜恭喜恭喜,我都没有面试机会,上周被压力炸了,今天中午看页面显示被捞进入评估结果下午就没了
京东三面373人在聊
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-25 17:26
点赞 评论 收藏
分享
评论
4
21
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务