Basic Calculator II
来源:互联网 发布:mac 翻译软件 编辑:程序博客网 时间:2024/05/17 21:40
该题和前面的"
Basic Calculator
"的处理方法一样,只是加入了对"*"、"/"两种运算的支持。class Solution {public: bool isnum(char c){ if(c >= '0' && c <= '9') return true; return false; } int calculate(string s) { vector<string> postorder; stack<char> ccache; stack<int> icache; string tmp; if(s.length() < 1) return 0;//构造后缀表达式 for(int i = 0; i < s.length(); ){ if(s[i] == ' '){ i++; continue; } if(!isnum(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; } if(s[i] == '*' || s[i] == '/'){ while(!ccache.empty() && ccache.top() != '(' && ccache.top() != '+' && ccache.top() != '-'){ tmp = ""; tmp += ccache.top(); postorder.push_back(tmp); ccache.pop(); } ccache.push(s[i]); i++; continue; } }else{ int j = i; while(j < s.length() && isnum(s[j])) 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, result; for(int i = 0; i < postorder.size(); i++){ if(postorder[i] == "+" || postorder[i] == "-" || postorder[i] == "*" || postorder[i] == "/"){ sec = icache.top(); icache.pop(); fir = icache.top(); icache.pop(); if(postorder[i] == "+") result = fir + sec; if(postorder[i] == "-") result = fir - sec; if(postorder[i] == "*") result = fir * sec; if(postorder[i] == "/") result = fir / sec; icache.push(result); }else{ icache.push(atoi(postorder[i].c_str())); } } return icache.top(); }};
0 0
- Basic Calculator & Basic Calculator II
- [LeetCode] Basic Calculator II
- Basic Calculator II
- [leetcode] Basic Calculator II
- leetcode Basic Calculator II
- Basic Calculator II
- 227Basic Calculator II
- 【LeetCode】Basic Calculator II
- Basic Calculator II
- [Leetcode]Basic Calculator II
- Basic Calculator II
- LeetCode227:Basic Calculator II
- Basic Calculator II
- Basic Calculator II
- Basic Calculator II(**)
- LeetCode Basic Calculator II
- [Leetcode]Basic Calculator II
- Basic Calculator II
- 题目1534:数组中第K小的数字
- Longest Substring Without Repeating Characters
- centos安装pycrypto
- 学习日志1---运用匈牙利命名法的命名规范,以及注释规范
- 大话设计模式(六 关于Flex的争论)
- Basic Calculator II
- hsacm 字符串训练之AB串
- 大话设计模式(七 工厂不好用了?)
- Extjs xx is undefined错误信息说明
- 解析nginx负载均衡
- JAVA学习第一天
- 放棋子
- Android网络框架-Volley(四) 使用get和post方法发送json请求
- CSS3去除手机浏览器按钮点击出现的高亮框