您的位置:首页 > 其它

LeetCode(224) Basic Calculator

2015-12-09 14:00 204 查看

题目

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 .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23


Note: Do not use the eval built-in library function.

分析

简易计算器的实现。

需要两个栈,一个存放操作数,另一个存放操作符。

注意事项:

加减法没有交换律,每个操作数入栈时,都需查看操作符栈若有 + 或 - ,立即计算更新两个栈。

当遇到)时,将当前()内的表达式计算结果入栈,同时检查操作符栈若有 + 或 - ,立即计算更新两个栈。

AC代码

class Solution {
public:
int calculate(string s) {
if (s.empty())
return 0;

//求出所给表达式的长度
int len = s.length();

//操作符栈
stack<char> op_stack;

//操作数栈
stack<int> num_stack;
for (int i = 0; i < len; ++i)
{
//(1) 跳过空格
if (s[i] == ' ')
continue;

//(2) 操作符入栈
else if (s[i] == '(' || s[i] == '+' || s[i] == '-')
{
op_stack.push(s[i]);
continue;
}//elif

//(3) 右括号
else if (s[i] == ')')
{
while (op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();

//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();

if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while

//弹出左括号
op_stack.pop();

//此时查看操作数和操作符栈
while (!op_stack.empty() && op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();

//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();

if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while
}//elif
else{
int num = 0;
while (i < len && isDigit(s[i]))
{
num = num * 10 + (s[i] - '0');
i++;
}//while
//回退一个字符
--i;
num_stack.push(num);

//此时查看操作数和操作符栈
while (!op_stack.empty() && op_stack.top() != '(')
{
//从数据栈弹出两个操作数
int num2 = num_stack.top();
num_stack.pop();
int num1 = num_stack.top();
num_stack.pop();

//从符号栈,弹出操作符
char op = op_stack.top();
op_stack.pop();

if (op == '+')
num_stack.push(num1 + num2);
else if (op == '-')
num_stack.push(num1 - num2);
}//while
}
}//for
return num_stack.top();
}

bool isDigit(char c)
{
if (c >= '0' && c <= '9')
return true;
else
return false;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: