224. Basic Calculator
2015-11-25 07:26
471 查看
题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
链接: http://leetcode.com/problems/basic-calculator/
题解:
刚开始以为要用和RPN一样的方法,其实不是的。可以one pass遍历整个数组并且得到结果。 需要使用一个栈来cache括号这种情况。
Time Complexity - O(n), Space Complexity - O(n)。
Reference:
https://leetcode.com/discuss/39553/iterative-java-solution-with-stack https://leetcode.com/discuss/41868/java-solution-stack https://leetcode.com/discuss/39479/simple-c-in-24-ms
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
Note: Do not use the
evalbuilt-in library function
链接: http://leetcode.com/problems/basic-calculator/
题解:
刚开始以为要用和RPN一样的方法,其实不是的。可以one pass遍历整个数组并且得到结果。 需要使用一个栈来cache括号这种情况。
Time Complexity - O(n), Space Complexity - O(n)。
public class Solution { public int calculate(String s) { if(s == null || s.length() == 0) return 0; Stack<Integer> stack = new Stack<>(); int result = 0, curNum = 0, sign = 1; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == ' ') continue; else if(Character.isDigit(c)) curNum = curNum * 10 + (int)(c - '0'); else if (c == '+') { result += sign * curNum; curNum = 0; sign = 1; } else if (c == '-') { result += sign * curNum; curNum = 0; sign = -1; } else if (c == '(') { stack.push(result); stack.push(sign); curNum = 0; sign = 1; result = 0; } else if (c == ')') { result += sign * curNum; curNum = 0; if(!stack.isEmpty()) result *= stack.pop(); if(!stack.isEmpty()) result += stack.pop(); } } if(curNum != 0) result += sign * curNum; return result; } }
Reference:
https://leetcode.com/discuss/39553/iterative-java-solution-with-stack https://leetcode.com/discuss/41868/java-solution-stack https://leetcode.com/discuss/39479/simple-c-in-24-ms
相关文章推荐
- DFS基础 (HDU 1010、HDU 1016、HDU 1072)
- QT:浮动的饼状统计图(自绘不规则窗口)
- 11月21日--11月30日(34小时,剩3279小时)
- 在QTableView中使用各种自定义委托
- Java EE 6 体系结构图
- QT:使用“状态模式”绘制界面
- Java EE 7 体系结构图
- C++ new和delete实现原理——new和delete最终调用malloc和free
- uboot 运行过程中的存储分布图解
- OSChina 周三乱弹 —— 如何判断程序员在做什么
- Qt中如何 编写插件 加载插件 卸载插件
- QT:用QSet储存自定义结构体的问题——QSet和STL的set是有本质区别的,QSet是基于哈希算法的,要求提供自定义==和qHash函数
- 树莓派安装kali后的简单配置
- PS5 MAC 破解补丁下载 以及激活方法
- 培训机构毕业的程序员被歧视的背后逻辑
- Something trivial. Type alias and const modifier
- 两种方法:VS2008下C++窗体程序显示控制台的方法——在QT程序中使用cout和cin
- 把自定义控件集成到Qt Designer中
- uboot - 启动流程分析【第二阶段】
- 单元测试的意义