0~10의 정수와 문자 S, D, T, *, #로 구성된 문자열이 입력될 시 총점수를 반환하는 함수를 작성하라.
-> 자세한 내용 보러가기
import java.util.*;
class Solution {
public int solution(String dartResult) {
int answer = 0;
Stack<Integer> stack = new Stack<>();
for(int idx = 0; idx < dartResult.length(); idx++){
char ch = dartResult.charAt(idx);
if(Character.isDigit(ch)){
//숫자라면 점수이다
int score = ch - '0';
if(Character.isDigit(dartResult.charAt(idx + 1))){
score *= 10;
idx++;
}
stack.push(score); //스택에 점수는 넣는다
}else{
//숫자가 아니라면, 점수 계산을 해야함
int prev = stack.pop(); //점수를 꺼내고 해당하는 로직에 맞춰 계산
//Single은 1제곱이므로 따로 계산하지 않는다
if(ch == 'D'){
prev = (int) Math.pow(prev, 2);
}else if(ch == 'T'){
prev = (int) Math.pow(prev, 3);
}else if(ch =='*'){
//스타상은 첫번째만 2배고 중첩 가능
if(!stack.isEmpty()){
int next = stack.pop() * 2;
stack.push(next);
}
prev *= 2;
}else if(ch == '#'){
prev *= (-1);
}
stack.push(prev);
}
}
while(!stack.isEmpty()){
answer += stack.pop();
}
return answer;
}
}