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

//通过分析我们找到哪种情况下括号是不能省略的:
//'+'对右边的'-'运算不能省略,
//'-'对右边的'+'和'-'运算,
//'*'对左边的'+'和'-'运算、对右边的'/''+''-'运算,
//'/'对左边的'+'和'-'以及对右边的所有运算不能省略 #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

相关推荐

小叮当411:应该是1-3个月吧
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 11:21
被夸真的超级开心,好可爱的姐姐
码农索隆:老色批们不用脑补了,我把金智妮的图找来了查看图片
点赞 评论 收藏
分享
评论
4
21
分享

创作者周榜

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