-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main.java
70 lines (56 loc) · 1.89 KB
/
Main.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
package _2020_카카오_인턴십.P2;
import java.util.*;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.solution("100-200*300-500+20")); // 60420
System.out.println(sol.solution("50*6-3*2")); // 300
}
}
class Solution {
char[][] opCases = {
{'+', '-', '*'},
{'+', '*', '-'},
{'-', '+', '*'},
{'-', '*', '+'},
{'*', '+', '-'},
{'*', '-', '+'}
};
public long solution(String expression) {
List<Long> numList = new ArrayList<>();
List<Character> opList = new ArrayList<>();
int idx = 0, n = expression.length();
while (idx < n) {
StringBuilder num = new StringBuilder();
while (idx < n && !isOp(expression.charAt(idx))) {
num.append(expression.charAt(idx++));
}
numList.add(Long.parseLong(num.toString()));
if (idx < n) opList.add(expression.charAt(idx++));
}
long ans = 0;
for (char[] op : opCases) {
List<Long> nums = new ArrayList<>(numList);
List<Character> ops = new ArrayList<>(opList);
for (int i = 0; i < 3; i++) {
int ofs;
while ((ofs = ops.indexOf(op[i])) >= 0) {
nums.add(ofs, calc(op[i], nums.get(ofs), nums.get(ofs+1)));
nums.remove(ofs+1);
nums.remove(ofs+1);
ops.remove(ofs);
}
}
ans = Math.max(ans, Math.abs(nums.get(0)));
}
return ans;
}
private boolean isOp(char c) {
return c == '+' || c == '*' || c == '-';
}
private long calc(char op, long a, long b) {
if (op == '*') return a*b;
else if (op == '+') return a+b;
else return a-b;
}
}