记录一下这个恶心的字符串模拟
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<char, int> mp;
string str;
stack<char> s;
cin >> str;
bool isFirst = true;
mp['-'] = 1, mp['+'] = 1;
mp['*'] = 2, mp['/'] = 2;
mp['('] = 3, mp[')'] = 3;
for (int i = 0; i < str.size(); i++)
{
if ((i == 0 || str[i - 1] == '(') && (str[i] == '+' || str[i] == '-') || (str[i] >= '0' && str[i] <= '9') || str[i] == '.') //读入运算数/正负号(区别于加减号)/小数点
{
if (!isFirst)
{
cout << " ";
}
if (str[i] != '+') //省略正号
cout << str[i];
while (str[i + 1] == '.' || (str[i + 1] >= '0' && str[i + 1] <= '9')) //处理多位数
{
i++;
cout << str[i];
}
isFirst = false;
}
else
{
if (str[i] == ')') //处理右括号
{
while (!s.empty() && s.top() != '(')
{
cout << " " << s.top();
s.pop();
}
s.pop(); //弹出左括号
}
else if (s.empty() || mp[str[i]] > mp[s.top()]) //如果栈空||当前运算符优先级大于栈顶运算符优先级
{
s.push(str[i]);
}
else //当前运算符优先级小于等于栈顶运算符优先级
{
while (!s.empty() && s.top() != '(')
{
cout << " " << s.top();
s.pop();
}
s.push(str[i]); //将当前运算符压栈
}
}
}
while (!s.empty()) //将剩余元素弹栈
{
cout << " " << s.top();
s.pop();
}
}