[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
the plus
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
library function.
算法描述:
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栈中的唯一一个数作为结果
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
evalbuilt-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栈中的唯一一个数作为结果
相关文章推荐
- 用qsort对字符串数组排序需要注意的几个问题
- JS操作GridView,JS获取table的td中的值跟控件
- shell脚本获得本机ip地址
- oracle 11g系列 用户管理实验报告
- Matlab与C++混合编程
- ios获取当前年月日和星期
- winform MDI子窗口闪动问题(本人测试100%有效解决闪屏问题)
- iOS汉字识别改进算法
- 获取网站访客手机号码哪个获取率高
- CommandBehavior.CloseConnection有何作用
- java 关于分页的实现
- iOS Widget简单使用
- Yii的getLastInsertID()注意事项
- 在一条语句中count出不同的条件
- SublimeText3: ImportError: No module named ‘urllib2′
- genymotion 使用技巧
- 把数组排成最小的数
- 如何判断Socket连接失效
- 正则爬取电影天堂电影信息
- Android 横竖屏操作