|
| 1 | +package _2020_카카오_인턴십.P2; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + public static void main(String[] args) { |
| 8 | + Solution sol = new Solution(); |
| 9 | + System.out.println(sol.solution("100-200*300-500+20")); // 60420 |
| 10 | + System.out.println(sol.solution("50*6-3*2")); // 300 |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +class Solution { |
| 15 | + |
| 16 | + char[][] opCases = { |
| 17 | + {'+', '-', '*'}, |
| 18 | + {'+', '*', '-'}, |
| 19 | + {'-', '+', '*'}, |
| 20 | + {'-', '*', '+'}, |
| 21 | + {'*', '+', '-'}, |
| 22 | + {'*', '-', '+'} |
| 23 | + }; |
| 24 | + |
| 25 | + public long solution(String expression) { |
| 26 | + |
| 27 | + List<Long> numList = new ArrayList<>(); |
| 28 | + List<Character> opList = new ArrayList<>(); |
| 29 | + |
| 30 | + int idx = 0, n = expression.length(); |
| 31 | + while (idx < n) { |
| 32 | + StringBuilder num = new StringBuilder(); |
| 33 | + while (idx < n && !isOp(expression.charAt(idx))) { |
| 34 | + num.append(expression.charAt(idx++)); |
| 35 | + } |
| 36 | + numList.add(Long.parseLong(num.toString())); |
| 37 | + if (idx < n) opList.add(expression.charAt(idx++)); |
| 38 | + } |
| 39 | + |
| 40 | + long ans = 0; |
| 41 | + for (char[] op : opCases) { |
| 42 | + List<Long> nums = new ArrayList<>(numList); |
| 43 | + List<Character> ops = new ArrayList<>(opList); |
| 44 | + |
| 45 | + for (int i = 0; i < 3; i++) { |
| 46 | + int ofs; |
| 47 | + while ((ofs = ops.indexOf(op[i])) >= 0) { |
| 48 | + nums.add(ofs, calc(op[i], nums.get(ofs), nums.get(ofs+1))); |
| 49 | + nums.remove(ofs+1); |
| 50 | + nums.remove(ofs+1); |
| 51 | + ops.remove(ofs); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + ans = Math.max(ans, Math.abs(nums.get(0))); |
| 56 | + } |
| 57 | + |
| 58 | + return ans; |
| 59 | + } |
| 60 | + |
| 61 | + private boolean isOp(char c) { |
| 62 | + return c == '+' || c == '*' || c == '-'; |
| 63 | + } |
| 64 | + |
| 65 | + private long calc(char op, long a, long b) { |
| 66 | + if (op == '*') return a*b; |
| 67 | + else if (op == '+') return a+b; |
| 68 | + else return a-b; |
| 69 | + } |
| 70 | +} |
0 commit comments