栈对于中缀表达式求值的应用:中缀——后缀——求值
中缀转后缀时可以直接返回两个队列?(返回字符串太慢了。。。)
代码如下(124ms/10.8MB):
string translate(string s) {
string result = "", temp = "";
for (int i = 0; i < s.size(); ++i) {
if (s[i] - '0' < 10 && s[i] - '0' >= 0) temp += s[i];
else {
if (temp != "") {
result += (temp + ' ');
temp = "";
}
if (s[i] == '(') punc.push(s[i]);
else if (s[i] == ')'||s[i] == '+' || s[i] == '-') {
while (!punc.empty()) {
if (punc.top() == '(') break;
result += punc.top();
punc.pop();
}
if(s[i] == ')') punc.pop();
else punc.push(s[i]);
}
else if (s[i] == '*' || s[i] == '/') {
while (!punc.empty()) {
if (punc.top() != '*' || punc.top() != '/') {
punc.push(s[i]);
break;
}
result += punc.top();
punc.pop();
}
}
}
}
if (temp != "") result += (temp + ' ');
while (!punc.empty()) {
result += punc.top();
punc.pop();
}
return result;
}
int calculate(string s) {
string sl = translate(s);
string temp = "";
for (int i = 0; i < sl.size(); ++i) {
if (sl[i] - '0' >= 0 && sl[i] - '0' < 10) temp += sl[i];
else if (sl[i] == ' ') {
num.push(stoi(temp));
temp = "";
}
else {
int n1 = num.top();
num.pop();
int n2 = num.top();
num.pop();
if (sl[i] == '+') num.push(n2 + n1);
else if (sl[i] == '-') num.push(n2 - n1);
else if (sl[i] == '*') num.push(n2 * n1);
else if (sl[i] == '/') num.push(n2 / n1);
}
}
return num.top();
}