-
Notifications
You must be signed in to change notification settings - Fork 1
/
BasicCalculatorIII.java
57 lines (51 loc) · 1.68 KB
/
BasicCalculatorIII.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.leetcode;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BasicCalculatorIII {
//https://leetcode.com/problems/basic-calculator-iii/
class Solution {
public int calculate(String s) {
Queue<Character> queue = new LinkedList<>();
for(char c : s.toCharArray()){
queue.offer(c);
}
queue.offer('+');
return calculateQueue(queue);
}
public int calculateQueue(Queue<Character> queue){
int result = 0;
int op = '+';
int num = 0;
Stack<Integer> stack = new Stack<>();
while(queue.size() > 0){
char ch = queue.poll();
if(ch == ' ') continue;
if(Character.isDigit(ch)){
num = num * 10 + ch -'0';
}else if(ch == '('){
num = calculateQueue(queue);//caclulate and update num
}else if(!Character.isDigit(ch)){
if(op == '+'){
stack.push(num);
}else if(op == '-'){
stack.push(-num);
}else if(op == '*'){
stack.push(stack.pop() * num);
}else if(op == '/'){
stack.push(stack.pop() / num);
}
op = ch;
num = 0;
}
if(ch == ')'){
break;
}
}
while(stack.size() > 0){
result += stack.pop();
}
return result;
}
}
}