Leetcode solution 227: Basic Calculator II
Problem Statement
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
evalbuilt-in library function.
Problem link
Video Tutorial
You can find the detailed video tutorial here
Thought Process
This problem is very similar to Basic Calculator. The difference is there is no parenthesis in this one, but there is * and / . We can use similar thought process by having two stacks, one stack for the operator and the other for the operands. We just need to pay attention the differentiate the operator's priority. For example, when you currently see a "+" or "-" and previous operator is "*" or "/", you need to pop up the operator stack and calculate. When you currently see a "*" or "/" and previous operator is "+" or "-", you should just keep pushing operator to stack. Else, they are at the same priority, we just do the normal calculation.
A few caveats
- Notice number overflow. "0- 2147483648". I don't think leetcode has this test case but it is a valid one. We should use Long.
- Pay attention to the order when popping out operands and calculate, the order matters.
- The number might not be just single digit, so need to read the char and convert the numbers
Solutions
Standard generic way
Keep two stacks, operator and operands as explained in the above "Thought Process"
public int calculate(String s) {
if (s == null || s.length() == 0) {
throw new IllegalArgumentException("invalid input");
}
int i = 0;
// even though leetcode does not have this use case System.out.println(ins.calculate("0-2147483648")); // -2147483648
// It can still pass with Integer, but use long for overflow case in general
Stack<Long> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
StringBuilder number = new StringBuilder(); // deal with non single digit numbers
while (i < s.length()) {
char c = s.charAt(i);
if (c == ' ') {
i++;
continue;
}
if (Character.isDigit(c)) {
number.append(c);
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
if (number.length() != 0) {
operands.push(Long.parseLong(number.toString()));
number = new StringBuilder();
}
// Basically based on different priority of operators
if (operators.isEmpty()) {
operators.push(c);
} else if (!operators.isEmpty() && (c == '*' || c == '/') && (operators.peek() == '+' || operators.peek() == '-')) {
// do nothing, keep pushing because */ has higher priority than +-
operators.push(c);
} else if (!operators.isEmpty() && (c == '+' || c == '-') && (operators.peek() == '*' || operators.peek() == '/')) {
// calculate all previous expressions
while (!operators.isEmpty()) {
operands.push(this.calculateValue(operands, operators.pop()));
}
operators.push(c);
} else {
// only calculating one step, for */, and +- case, one step is fine
operands.push(this.calculateValue(operands, operators.pop()));
operators.push(c);
}
}
i++;
}
if (number.length() != 0) {
operands.push(Long.parseLong(number.toString()));
}
// for "3+2*2" case that's why we need a while loop
while (!operators.isEmpty()) {
operands.push(this.calculateValue(operands, operators.pop()));
}
return (int)operands.pop().longValue(); // Since it is Long, an object can't be cast to primitive, .longValue first then cast
}
private long calculateValue(Stack<Long> operands, char op) {
long o2 = operands.pop();
long o1 = operands.pop();
if (op == '+') {
return o1 + o2;
} else if (op == '-') {
return o1 - o2;
} else if (op == '*') {
return o1 * o2;
} else if (op == '/') {
return o1 / o2;
} else {
throw new IllegalArgumentException("invalid op!");
}
}
Time Complexity: O(N), N is the length of the string
Space Complexity: O(N), extra stack is needed
Use one stack with two passes
Another neat and clean way to solve this problem is also similar to the "Use the sign method with one stack" in Basic Calculator. The idea is in the first pass, only calculate "*" and "/" and push the values into the stack, then have a 2nd pass to do the "+" and "-" calculations.
// Another thought is having 2 pass, first pass */, second pass +-
// "1 + 2 * 3 / 2" = 4, pretty clean
// "1 - 2 * 3 / 2" = -2
public int calculateTwoPass(String s) {
int len;
if (s == null || (len = s.length()) == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
// This is more like the previous sign
char sign = '+';
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
} if ((!Character.isDigit(s.charAt(i)) && ' ' != s.charAt(i)) || i == len - 1) {
if (sign == '-') {
stack.push(-num);
}
if (sign == '+') {
stack.push(num);
}
if (sign == '*') {
stack.push(stack.pop()*num);
}
if (sign == '/') {
stack.push(stack.pop()/num);
}
// reassign the current sign
sign = s.charAt(i);
num = 0;
}
} int re = 0;
for (int i : stack){
re += i;
}
return re;
}
Time Complexity: O(N), N is the length of the string
Space Complexity: O(N), extra stack is needed
References
Leetcode solution 227: Basic Calculator II的更多相关文章
- 【LeetCode】227. Basic Calculator II 解题报告(Python)
[LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...
- 【LeetCode】227. Basic Calculator II
Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...
- leetcode 224. Basic Calculator 、227. Basic Calculator II
这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...
- [LeetCode] 227. Basic Calculator II 基本计算器之二
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- [LeetCode] 227. Basic Calculator II 基本计算器 II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- LeetCode#227.Basic Calculator II
题目 Implement a basic calculator to evaluate a simple expression string. The expression string contai ...
- (medium)LeetCode 227.Basic Calculator II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- Java for LeetCode 227 Basic Calculator II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- 224. Basic Calculator + 227. Basic Calculator II
▶ 两个四则表达式运算的题目,第 770 题 Basic Calculator IV 带符号计算不会做 Orz,第 772 题 Basic Calculator III 要收费 Orz. ▶ 自己的全 ...
随机推荐
- C++ 洛谷P1230 智力大冲浪
题目描述 小伟报名参加中央电视台的智力大冲浪节目.本次挑战赛吸引了众多参赛者,主持人为了表彰大家的勇气,先奖励每个参赛者m元.先不要太高兴!因为这些钱还不一定都是你的?!接下来主持人宣布了比赛规则: ...
- C# 创建Windows服务demo
一.准备工作 1.操作系统:Windows 10 X64 2.开发环境:VS2017 3.编程语言:C# 4. .NET版本:.NET Framework 4.5 二.创建Windows Servic ...
- 一、JavaScript概述
1.Javascript是什么?可以做什么? 1) JavaScript是一种基于对象和事件驱动的解释性脚本语言, 它具有与Java和C语言类似的语法. 2) JavaScript可直接嵌 ...
- Django rest framework(3)----节流
目录 Django组件库之(一) APIView源码 Django restframework (1) ----认证 Django rest framework(2)----权限 Django res ...
- Hash的应用2
代码: #include <stdio.h> #define OFFSET 500000//偏移量 ];//记录每个数是否出现,出现为1,不出现为0 int main(){ int n,m ...
- Web前端_微信小程序实战开发
微信小程序开发实战教程 一.微信小程序 它是一种混合开发的方式. 是安装在微信中的程序(一个程序最多2M空间). 1.1 注册 1 2 点击立即注册:进入下方页面 3 4 点击小程序进入表单填写页 ...
- Jmeter自定义Java请求开发
一.本次实验目的 IDEA新建maven项目,使用java开发自定义jmeter的请求. 本次开发使用的代码,会百度云分享给大家. 二.本次实验环境 Idea 2017.02 Jmeter 5.1.1 ...
- css基础5
今天在这里跟大家分享css基础最核心的部分,浮动和定位.话不多说,直接上干货! 一.浮动 定义:定位元素是相对于其正常位置应该出现的位置.定位元素的位置是相对于自身.父级元素位置.其他元素以及浏览器窗 ...
- Git常用操作指南
目录 前言 Git简介 安装之后第一步 创建版本库 本地仓库 远程仓库 版本控制 工作区和暂存区 版本回退 撤销修改 删除文件 分支管理 创建与合并分支 解决冲突 分支管理策略 状态存储 多人协作 R ...
- [leetcode] 264. Ugly Number II (medium)
263. Ugly Number的子母题 题目要求输出从1开始数,第n个ugly number是什么并且输出. 一开始想着1遍历到n直接判断,超时了. class Solution { public: ...