카카오 - 다트게임

greenTea·2023년 7월 25일
0
import java.util.*;
import java.util.stream.*;

class Solution {
    public int solution(String dartResult) {
         Stack<Integer> stack = new Stack<>();
    
            for (int i=0;i<dartResult.length();i++) {
                char c = dartResult.charAt(i);
                if (c=='1' && dartResult.charAt(i+1) =='0') {
                    stack.push(10);
                    i++;
                    continue;
                }

                switch (c) {
                    case '*' -> {
                         int f1  = stack.pop();
                        if (stack.size() >= 1) {
                            int f2  = stack.pop();
                            stack.push(f2* 2);
                        }
                        stack.push(f1* 2);
                    }
                    case '#' -> {
                        int f1  = stack.pop();
                        stack.push(-f1);
                    }
                    case 'S' -> {
                        int f1  = stack.pop();
                        stack.push(f1);
                    }
                    case 'D' -> {
                        int f1  = stack.pop();
                        stack.push(f1* f1);
                    }
                    case 'T' -> {
                        int f1  = stack.pop();
                        stack.push(f1* f1*f1);
                    }
                    default ->  {
                        stack.push(c - '0');
                    }
                }
            }
            
            return stack.stream().mapToInt(i -> i).sum();
        }
    }

🥳switch문을 이용하여 종류별로 해당 로직을 작성하여 풀이하였습니다.

🤔먼저 charAt를 통해 값을 가져옵니다. 이때 1~10까지의 숫자가 들어올 수 있다고 하였는데 10의 경우를 체크하기 위해서 c=='1' && dartResult.charAt(i+1) =='0'를 통해 확인하고 값이 10이라면 stack에 넣어주고 다음 차례로 넘깁니다.

🧐switch문 에서는 stack에 있는 값을 활용하여 각 값에 맞는 로직을 설정해주었습니다.
(stack을 사용하면 보다 더 편리하게 값을 넣었다 뺏다 할 수 있기에 사용하였습니다. 이 때 stack.pop()의 경우 empty stack일 수 있으니 이 경우에만 조심해주시면 될 것 같습니다)

출처 : 프로그래머스 스쿨

profile
greenTea입니다.

0개의 댓글