[LeetCode]Basic Calculator
2016-03-30 13:52
387 查看
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.
用堆栈来做,注意处理好字符串的空格,和各种CornerCase。思路不复杂,但是细节要注意。
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.
用堆栈来做,注意处理好字符串的空格,和各种CornerCase。思路不复杂,但是细节要注意。
class Solution { public: int calculate(string s) { stack<int> num; stack<char> op; int front = 0; int next = 0; //记录前一个符号和后一个符号 s = '(' + s + ')'; op.push('('); for(int i=1; i<s.size(); i++){ if(s[i]==' ') continue; //空格处理跳过 if(s[i]=='+'||s[i]=='-'||s[i]=='('||s[i]==')'){ next = i; if(!allwhite(s,front,next))//判断两个符号间是否全是空格 num.push(atoi(s.substr(front+1,next-front-1).c_str()));//提取数字 front = next; op.push(s[i]); } if(op.top()==')') // 出栈逻辑 { op.pop(); int temp = 0; while(true) { if(op.top()=='+'){ int a = num.top(); temp = temp + a; num.pop(); op.pop(); } if(op.top()=='-'){ int a = num.top(); num.pop(); temp = temp - a; op.pop(); } if(op.top()=='('){ int a = num.top(); temp = temp + a; num.pop(); num.push(temp); op.pop(); break; } } } } return num.top(); } bool allwhite(string &s,int i,int j){ if(j==i) return true; for(int k=i+1; k<j; k++){ if(s[k]!=' ') return false; } return true; } };
相关文章推荐
- C++ []lambda表达式
- 正则实现String的trim方法
- cocos2dx 对象属性设置
- linux硬盘挂载-新硬盘挂载和扩容硬盘挂载
- iOS App性能优化
- 重写与重载规则
- iOS App性能优化
- Android性能优化之Bitmap的内存优化
- k-means聚类算法python实践
- 结构体的初始化与赋值
- 基于libuinet的IPv6调试
- 怎样防止hosts被软件自动修改
- 基于libuinet的IPv6调试
- Web开发入门
- C++ 重载函数调用运算符
- iOS Provisioning Profile(Certificate)与Code Signing详解
- 我的 Android 开发实战经验总结
- 利用命令切换CTabCtrl控件的Tab页面
- 自定义网络请求图片的大小
- 函数式编程