본문 바로가기
Problem Solving

[프로그래머스] L2 수식 최대화 / 2020 카카오 인턴십 (Java)

by JYHAN 2020. 12. 19.

카카오

[프로그래머스] L2 수식 최대화 / 2020 카카오 인턴십

[풀이]

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
import java.util.*;
class Solution {
    static List<String> nums = new ArrayList<String>();
    static List<String> ops = new ArrayList<String>();
    static boolean[] chk = new boolean[3];
    static String[] op = new String[]{"+","-","*"};
    static int[] prior = new int[3];
    static Long answer = Long.MIN_VALUE;
    
    public long solution(String exp) {
        String temp = "";
        for(int i=0; i<exp.length(); i++){
            if('0'<= exp.charAt(i) && exp.charAt(i) <='9')
                temp += Character.toString(exp.charAt(i));
            else{
                nums.add(temp);
                ops.add(Character.toString(exp.charAt(i)));
                temp = "";
            }
        }
        if(!temp.equals("")) nums.add(temp);
        solve(0);
        return answer;
    }
    static Long cal(Long n1, Long n2, String operation){
        if(operation.equals("+")){
            return n1+n2;
        }
        else if(operation.equals("-")){
            return n1-n2;
        }
        else {
            return n1*n2;
        }
    }
    static void solve(int cnt){
        if(cnt==3){
            List<String> tNums = new ArrayList<String>();
            List<String> tOps = new ArrayList<String>();
            for(int i=0; i<nums.size(); i++) tNums.add(nums.get(i));
            for(int i=0; i<ops.size(); i++) tOps.add(ops.get(i));
            
            for(int i=0; i<3; i++){ // 연산자 우선순위대로 계산
                String oopp = op[prior[i]];
                for(int j=0; j<tOps.size(); j++){
                    if(tOps.get(j).equals(oopp)){ // 연산자가 일치한 경우
                        tOps.remove(j);
                        long n1 = Long.parseLong(tNums.get(j));
                        long n2 = Long.parseLong(tNums.get(j+1));
                        tNums.remove(j+1);
                        tNums.remove(j);
                        String ret = Long.toString(cal(n1, n2, oopp));
                        tNums.add(j, ret);
                        j--;
                    }
                }
            }
            long num = Math.abs(Long.parseLong(tNums.get(0)));
            if(answer<num) answer = num;
            return;
        }
        
        for(int i=0; i<3; i++){
            if(chk[i]) continue;
            chk[i] = true;
            prior[cnt] = i;
            solve(cnt+1);
            chk[i] = false;
        }
    }
}
cs

댓글