题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
Example 1:
Input: "1 + 1" Output: 2
Example 2:
Input: " 2-1 + 2 " Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)" Output: 23
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
代码:
class Solution {
public:
int calculate(string s) {
stack<char> ops;
stack<int> nums;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ')continue;
if (isdigit(s[i])) {
string temp = "";
while (isdigit(s[i])) {
temp.push_back(s[i]); i++;
}
i--;
int tempint;
stringstream ss;
ss << temp;
ss >> tempint;
if (!ops.empty()&&ops.top() != '(') {
char op = ops.top(); ops.pop();
if (op == '+') {
tempint += nums.top();
nums.pop();
}
if (op == '-') {
tempint = nums.top() - tempint;
nums.pop();
}
}
nums.push(tempint);
}
else if (s[i] == ')') {
ops.pop();
while (!ops.empty()&&ops.top()!='(') {
char op = ops.top(); ops.pop();
int a = nums.top(); nums.pop();
int b = nums.top(); nums.pop();
if (op == '-') {
nums.push(b-a);
}
if (op == '+') {
nums.push(a + b);
}
}
}
else ops.push(s[i]);
}
return nums.top();
}
};
思路:
使用两个栈来存储信息,一个栈是字符串栈,存储符号;一个栈是数字栈,存储运算的数。遍历字符串,遇到空格是continue,遇到数字的时候,读取他所在位置的后连起来的所有数字,组成一个数,判断opts栈顶的符号,如果符号不是(,那么取出符号和它nums栈顶的数,根据符号,将两个数根据该符号进行运算,运算结果再push到数字栈中;如果遇到的符号是')',那么pop出符号栈顶的那个符号(这个符号一定是‘(’),然后对符号栈和数栈一直进行符号运算并push进数栈的操作,知道碰到了‘(’符号或者符号栈为空。最后运算结束后,数栈中只剩下最后一个元素,那就是最后的运算结果,返回即可。