224. Basic Calculator
来源:互联网 发布:中南大学网络教育电话 编辑:程序博客网 时间:2024/06/16 14:45
- Problem Description
- Implementation By C
Problem Description
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"(8)" = 8"" = 0"2-(5-6)" = 3Note: Do not use the eval built-in library function.
This problem can be well solved by stack. We utilize two stacks with operation type stack and operand stack. When we meet with number, we push the whole number into operand stack. When we meet with operation and ‘(’ we push it to operation stack. When we meet across ‘)’ we need do operation pop operands and operation type from stacks until we meet with ‘(‘. In the end, we pop the operands and operation until there is no operation in operation stack.
Implementation By C++
class Solution {public: int calculate(string s) { stack<int> num; stack<char> ope; int str_len = s.size(); int res = 0; int tmp = 0; if(str_len == 0) return res; for(int idx = 0; idx < str_len; idx++) { if(isdigit(s[idx])) { tmp = tmp*10 + s[idx] - '0'; if(idx == str_len - 1 || !isdigit(s[idx+1])) { num.push(tmp); tmp = 0; } } else if(s[idx] == ')') { while(ope.top() != '(') { if(num.size() > 1) { int op1 = num.top(); num.pop(); int op2 = num.top(); num.pop(); char ope_type = ope.top(); ope.pop(); num.push(op2+op1*(ope_type == '+'?1:-1)); } } ope.pop(); } else if(s[idx] == '(') ope.push(s[idx]); else if(s[idx] == '+' || s[idx] == '-') { if(ope.size() > 0 && ope.top() != '(') { int op1 = num.top(); num.pop(); int op2 = num.top(); num.pop(); char ope_type = ope.top(); ope.pop(); num.push(op2+op1*(ope_type == '+'?1:-1)); } ope.push(s[idx]); } } while(ope.size() > 0) { int op1 = num.top(); num.pop(); int op2 = num.top(); num.pop(); char ope_type = ope.top(); ope.pop(); num.push(op2+op1*(ope_type == '+'?1:-1)); } return num.top(); }};
阅读全文
1 0
- 224. Basic Calculator 227. Basic Calculator II
- 224.Basic Calculator
- 224.Basic Calculator
- [leetcode] 224.Basic Calculator
- [leetcode] 224. Basic Calculator
- Leetcode-224.Basic Calculator
- [LeetCode]224. Basic Calculator
- 224. Basic Calculator
- 224. Basic Calculator
- leetcode 224. Basic Calculator
- 224. Basic Calculator
- leetcode.224. Basic Calculator
- LeetCode-224.Basic Calculator
- 224. Basic Calculator
- 224. Basic Calculator
- 224. Basic Calculator
- 224. Basic Calculator
- [LeetCode]224. Basic Calculator
- 2018计算机考研认识
- python基础笔记-3
- 个人学习总结一机器学习入门(九)
- ajax如何设置同步
- ★★★★★图说C++对象模型:对象内存布局详解
- 224. Basic Calculator
- 文章标题
- 各种width,offsetWidth, getBoundingClientRect(), clientWidth,scrollWidth区别
- 手机扫描识别,扫描名片识别信息
- 2017计蒜之道 第四场 商汤科技的安全令牌
- 【sqlite乱码已解决2017-06】SQLite数据库的乱码解决办法
- 伪目标
- Compile chromium OS on Debian
- python中的ORM