您的位置:首页 > 其它

[leetcode][math] Basic Calculator

2015-06-13 18:10 337 查看
题目:

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.
class Solution {
public:
int calculate(string s) {
if (s.empty()) return 0;
stack<char> op;
stack<int> nums;
int i = 0;
while (s[i] != '\0')
{
if (s[i] >= '0' && s[i] <= '9'){
int val = 0;
while (s[i] >= '0' && s[i] <= '9')
{
val = val * 10 + (s[i] - '0');
++i;
}
nums.push(val);
}
else if(s[i] == '('){
op.push(s[i]);
++i;
}
else if(s[i] == '+' || s[i] == '-'){

if (op.empty() || op.top() == '('){
op.push(s[i]);
}
else {
while (!op.empty() && op.top() != '(')
{
oneCalculate(nums, op);
}
op.push(s[i]);
}
++i;
}
else if(s[i] == ')'){
while (op.top() != '(')
{
oneCalculate(nums, op);
}
op.pop();//弹出'('
++i;
}
else//空格
{
++i;
}
}
while (!op.empty())
{
oneCalculate(nums, op);
}
return nums.top();
}
private:
void oneCalculate(stack<int> &nums, stack<char> &op){
int v1 = nums.top();
nums.pop();
int v2 = nums.top();
nums.pop();
int val;
if (op.top() == '+'){
nums.push(v2 + v1);
}
else if (op.top() == '-'){
nums.push(v2 - v1);
}
op.pop();
}
};


算法描述:
1.创建两个栈,一个存放操作数(nums),一个存放运算符(op)。

2.依次遍历中序表达式字符串的每个字符

1).如是数字字符,将从该字符开始的连续出现的数字字符组成的字符串转化为int,并压入nums栈

2).如果是'(',直接压入op栈。注:‘(’的优先级最低

3).如果是‘+’或‘-’,若op栈为空或为'(',则直接压入op栈(它们的优先级都比‘+’和‘-’低);否则,弹出op栈顶元素,从nums栈弹出两个操作数做相应运算,将结果放入nums栈,然后将当前元素('+'或'-')压入op栈。注:栈中的‘+’和‘-’比栈外的‘+’和‘-’优先级高。

4).如果是')',弹出op栈顶的元素和两个nums栈的操作数做相应运算并将结果压入nums栈,重复此操作直至遇到'(',弹出'('

5).如果是‘ ’,不做任何操作

3.如果op栈不为空,弹出这个唯一的运算符和nums中最后的两个操作数做相应操作并将结果压入nums栈

4.返回nums栈中的唯一一个数作为结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: