Basic Calculator
2015-07-14 12:56
441 查看
该题的思路很明确就是将中缀表达式转换为后缀表达式,然后通过后缀表达式来求值。
class Solution {
public:
int calculate(string s) {
vector<string> postorder;
stack<char> ccache;
stack<int> icache;
string tmp;
int len = s.length();
if(s.length() < 1)
return 0;
//构造后缀表达式
for(int i = 0; i < len; ){
if(s[i] == ' '){
i++;
continue;
}
if(s[i] == '+' || s[i] == '-' || s[i] == '(' || s[i] == ')'){
if(s[i] == '(' || ccache.empty()){
ccache.push(s[i]);
i++;
continue;
}
if(s[i] == ')'){
while(ccache.top() != '('){
tmp = "";
tmp += ccache.top();
postorder.push_back(tmp);
ccache.pop();
}
ccache.pop();
i++;
continue;
}
if(s[i] == '+' || s[i] == '-'){
while(!ccache.empty() && ccache.top() != '(' ){
tmp = "";
tmp += ccache.top();
postorder.push_back(tmp);
ccache.pop();
}
ccache.push(s[i]);
i++;
continue;
}
}else{
int j = i;
while(j < len && s[j] >= '0' && s[j] <= '9')
j++;
tmp = "";
tmp = s.substr(i, j - i);
postorder.push_back(tmp);
i = j;
}
}
//将栈中剩余的元素全部添加到后缀表达式字串中
while(!ccache.empty()){
tmp = "";
tmp += ccache.top();
ccache.pop();
postorder.push_back(tmp);
}
class Solution {
public:
int calculate(string s) {
vector<string> postorder;
stack<char> ccache;
stack<int> icache;
string tmp;
int len = s.length();
if(s.length() < 1)
return 0;
//构造后缀表达式
for(int i = 0; i < len; ){
if(s[i] == ' '){
i++;
continue;
}
if(s[i] == '+' || s[i] == '-' || s[i] == '(' || s[i] == ')'){
if(s[i] == '(' || ccache.empty()){
ccache.push(s[i]);
i++;
continue;
}
if(s[i] == ')'){
while(ccache.top() != '('){
tmp = "";
tmp += ccache.top();
postorder.push_back(tmp);
ccache.pop();
}
ccache.pop();
i++;
continue;
}
if(s[i] == '+' || s[i] == '-'){
while(!ccache.empty() && ccache.top() != '(' ){
tmp = "";
tmp += ccache.top();
postorder.push_back(tmp);
ccache.pop();
}
ccache.push(s[i]);
i++;
continue;
}
}else{
int j = i;
while(j < len && s[j] >= '0' && s[j] <= '9')
j++;
tmp = "";
tmp = s.substr(i, j - i);
postorder.push_back(tmp);
i = j;
}
}
//将栈中剩余的元素全部添加到后缀表达式字串中
while(!ccache.empty()){
tmp = "";
tmp += ccache.top();
ccache.pop();
postorder.push_back(tmp);
}
//通过后缀表达式求值 int fir, sec; for(int i = 0; i < postorder.size(); i++){ if(postorder[i] == "+" || postorder[i] == "-"){ sec = icache.top(); icache.pop(); fir = icache.top(); icache.pop(); if(postorder[i] == "+") icache.push(fir + sec); if(postorder[i] == "-") icache.push(fir - sec); }else{ icache.push(atoi(postorder[i].c_str())); } } return icache.top(); } }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- 样式表CSS布局经验
- 路由器之基本维护经验
- C#中struct和class的区别详解
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PostgreSQL ERROR: invalid escape string 解决办法
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结