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