如何评估仅由+
and*
运算符组成的中缀字符串表达式。(无括号)。
示例 1:
- 输入:
"1+2*3"
- 输出:
7
示例 2:
- 输入:
"1+2*3+4"
- 输出:
11
这是我到目前为止的代码(没有给出正确的结果),我想知道我是否可以用一个堆栈(或没有)来完成
int evaluateExpression(string s) {
stack<int> operandStack;
stack<char> operatorStack;
string token = "";
for(char &c : s) {
if(c == '*' || c == '+') {
operandStack.push(stoi(token));
operatorStack.push(c);
token = "";
}
else {
token += c;
}
if(operandStack.size() > 1
&& operandStack.size() == operatorStack.size() + 1
&& operatorStack.top() == '*') {
int a = operandStack.top(); operandStack.pop();
int b = operandStack.top(); operandStack.pop();
operandStack.push(a * b);
}
}
while(operandStack.size() > 1) {
int a = operandStack.top(); operandStack.pop();
int b = operandStack.top(); operandStack.pop();
operandStack.push(a + b);
}
return operandStack.top();
}
注意:不想使用任何非标准库。理想情况下不使用任何库。