-
Notifications
You must be signed in to change notification settings - Fork 2
/
BasicCalculator.java
112 lines (94 loc) · 2.56 KB
/
BasicCalculator.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.algorithm.playground.leetcode.problems.lc200.lc220.lc224;
import java.util.LinkedList;
import java.util.regex.Pattern;
/**
* https://leetcode.com/problems/basic-calculator/description/
*/
public class BasicCalculator {
class Solution {
private final Pattern IS_NUMBER = Pattern.compile("\\d+");
public int calculate(String s) {
LinkedList<Integer> numbers = new LinkedList<>();
LinkedList<String> ops = new LinkedList<>();
String[] expression = parse(s);
for (String part : expression) {
if (IS_NUMBER.matcher(part).matches()) {
numbers.push(Integer.valueOf(part));
} else {
if (")".equals(part)) {
ops.poll();
} else {
ops.push(part);
continue;
}
}
if (numbers.size() > 1 && !"(".equals(ops.peek())) {
Integer arg2 = numbers.poll();
//noinspection ConstantConditions
numbers.push(calculate(numbers.poll(), ops.poll(), arg2));
}
}
//noinspection ConstantConditions
return numbers.poll();
}
private Integer calculate(Integer i1, String op, Integer i2) {
switch (op) {
case "+":
return i1 + i2;
case "-":
return i1 - i2;
default:
throw new UnsupportedOperationException(String.format("Operation %s is not supported", op));
}
}
private String[] parse(String s) {
s = s.replaceAll("\\s+", "");
return s.split("(?<=[-+*/()])|(?=[-+*/()])");
}
}
class SolutionFast {
public int calculate(String s) {
LinkedList<Integer> numbers = new LinkedList<>();
LinkedList<Character> ops = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char part = s.charAt(i);
if (' ' == part) {
continue;
}
if (Character.isDigit(part)) {
int ii = part - '0';
while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {
ii = ii * 10 + (s.charAt(i + 1) - '0');
i++;
}
numbers.push(ii);
} else {
if (')' == part) {
ops.poll();
} else {
ops.push(part);
continue;
}
}
//noinspection ConstantConditions
if (numbers.size() > 1 && !('(' == ops.peek())) {
Integer arg2 = numbers.poll();
//noinspection ConstantConditions
numbers.push(calculate(numbers.poll(), ops.poll(), arg2));
}
}
//noinspection ConstantConditions
return numbers.poll();
}
private Integer calculate(Integer i1, Character op, Integer i2) {
switch (op) {
case '+':
return i1 + i2;
case '-':
return i1 - i2;
default:
throw new UnsupportedOperationException(String.format("Operation %s is not supported", op));
}
}
}
}