59 lines
1.3 KiB
C++
59 lines
1.3 KiB
C++
#include <bits/stdc++.h>
|
||
using namespace std;
|
||
|
||
/*
|
||
中缀的逻辑表达式 转 后缀的逻辑表达式
|
||
|
||
测试用例1:
|
||
0&(0|1|0)
|
||
|
||
答案:
|
||
001|0|&
|
||
|
||
测试用例2:
|
||
1|0&1&(0|1|0)|(0&1)
|
||
|
||
答案:
|
||
101&01|0|&|01&|
|
||
*/
|
||
unordered_map<char, int> h{{'|', 1}, {'&', 2}};
|
||
string s;
|
||
string t;
|
||
stack<char> stk;
|
||
int main() {
|
||
cin >> s;
|
||
for (int i = 0; i < s.size(); i++) {
|
||
if (isdigit(s[i])) {
|
||
int x = 0;
|
||
while (i < s.size() && isdigit(s[i])) {
|
||
x = x * 10 + s[i] - '0';
|
||
i++;
|
||
}
|
||
i--;
|
||
t.append(to_string(x));
|
||
} else if (isalpha(s[i]))
|
||
t.push_back(s[i]);
|
||
else if (s[i] == '(')
|
||
stk.push(s[i]);
|
||
else if (s[i] == ')') {
|
||
while (stk.top() != '(') {
|
||
t.push_back(stk.top());
|
||
stk.pop();
|
||
}
|
||
stk.pop();
|
||
} else {
|
||
while (stk.size() && h[s[i]] <= h[stk.top()]) {
|
||
t.push_back(stk.top());
|
||
stk.pop();
|
||
}
|
||
stk.push(s[i]);
|
||
}
|
||
}
|
||
while (stk.size()) {
|
||
t.push_back(stk.top());
|
||
stk.pop();
|
||
}
|
||
// printf("%s", t.c_str());
|
||
cout << t << endl;
|
||
return 0;
|
||
} |