lintcode-表达式求值-368
2015-10-15 20:46
351 查看
给一个用字符串表示的表达式数组,求出这个表达式的值。
样例
对于表达式
其值为
注意 表达式只包含
样例
对于表达式
(2*6-(23+7)/(1+2)), 对应的数组为:
[ "2", "*", "6", "-", "(", "23", "+", "7", ")", "/", (", "1", "+", "2", ")" ],
其值为
2
注意 表达式只包含
整数,
+,
-,
*,
/,
(,
)
解题思路:
step1:把中缀表达式转换成后缀表达式
step2:通过后缀表达式求值
class Solution { public: void init(){ level["+"]=1; level["-"]=1; level["*"]=2; level["/"]=2; level["("]=3; } void step1(vector<string> &s){ for(auto &e:s){ if(e[0]<='9'&&'1'<=e[0]) ex.push_back(e); else if(e==")"){ while(!st.empty()&&st.top()!="("){ ex.push_back(st.top()); st.pop(); } st.pop(); } else{ while(!st.empty()&&st.top()!="("&&level[e]<=level[st.top()]){ ex.push_back(st.top()); st.pop(); } st.push(e); } } while(!st.empty()){ ex.push_back(st.top()); st.pop(); } } int step2(){ for(auto &e:ex){ if(e[0]<='9'&&e[0]>='0'){ st2.push(stoi(e)); continue; } int a=st2.top(); st2.pop(); int b=st2.top(); st2.pop(); if(e=="+") st2.push(b+a); else if(e=="-") st2.push(b-a); else if(e=="*") st2.push(b*a); else st2.push(b/a); } return st2.top(); } int evaluateExpression(vector<string> &expression) { if(expression.empty()) return 0; init(); step1(expression); return step2(); } private: stack<int> st2; stack<string> st; vector<string> ex; map<string,int> level; };
相关文章推荐
- UIViewController之间传递值的两种方式
- 数据结构 动态可调数组 顺序栈
- 安卓外部存储路径,吐司的优化问题
- 渐变图形---音频条形图
- [置顶] 集成VIM强大的代码编辑器(二)
- KVM - virsh常用操作
- Matlab的libsvm-3.20的安装
- (非原创)JAVA学习(二)单例模式
- Android各种颜色dawable.xml中定义
- win7 下mingw64 编译boost 1.59
- [百度之星复赛T5]
- 两个时间进行比较 使用NSCalendar 日历类进行对比
- 安卓开发环境安装--菜鸟之路(三)
- universal image loader学习笔记
- fpga简易流水灯
- 乐讯机器人高级版【版本认证20151015】
- webapi 在POST时的坑以及OracleCommand的参数绑定的坑
- 转:C#索引器
- 用户和用户组的简单总结
- 用层次分析法解决手机选择困难症