351. [1차] 다트 게임

김해준's avatar
Mar 17, 2026
351. [1차] 다트 게임

언어 : Java

문제

notion image
notion image
notion image

풀이 코드

class Solution { public int solution(String dartResult) { int answer = 0; int[] myScore = new int[3]; String[] result = new String[3]; int scoreIndex = 0; for(int i = 0 ; i < dartResult.length(); i += 2){ char c1 = dartResult.charAt(i); char c2 = dartResult.charAt(i + 1); String convert = ""; convert+= c1; if(Character.isDigit(c2)){ convert+=c2; i++; } int score = Integer.parseInt(convert); String bonus = ""; char c3 = dartResult.charAt(i + 1); bonus += c3; if(bonus.equals("D")){ score *= score; }else if(bonus.equals("T")){ int origin = score; score *= origin; score *= origin; } myScore[scoreIndex] = score; scoreIndex++; if(i + 2 < dartResult.length()){ char c4 = dartResult.charAt(i + 2); if(!Character.isDigit(c4)){ String option = ""; option += c4; if(option.equals("*")){ myScore[scoreIndex - 1] *= 2; if(scoreIndex - 1 > 0){ myScore[scoreIndex - 2] *= 2; } }else if(option.equals("#")){ myScore[scoreIndex - 1] *= -1; } i++; } } } for(int i = 0 ; i < myScore.length; i++){ answer+= myScore[i]; } return answer; } }

풀이 해설

1. 문제 개요

다트 게임은 총 3번의 라운드로 진행된다.
각 라운드는 다음과 같은 구조를 가진 문자열로 표현된다.
점수 + 보너스 + 옵션(선택)
예시
1S2D*3T
구성 요소
요소
의미
점수
0~10
S
1제곱
D
2제곱
T
3제곱
*
현재 점수와 이전 점수 2배
#
현재 점수 음수

2. 변수 설명

int[] myScore = new int[3];
각 라운드의 점수를 저장하는 배열이다.
다트 게임은 항상 3번 던지므로 크기는 3이다.
[라운드1 점수, 라운드2 점수, 라운드3 점수]

int scoreIndex = 0;
현재 몇 번째 라운드를 처리하는지 나타낸다.

3. 문자열 순회

for(int i = 0 ; i < dartResult.length(); i += 2)
문자열을 앞에서부터 읽으며 점수를 해석한다.
하지만 실제로는
  • 점수가 10일 수도 있고
  • 옵션이 있을 수도 있기 때문에
코드 내부에서 i++를 추가로 증가시키며 처리한다.

4. 기본 점수 추출

char c1 = dartResult.charAt(i); char c2 = dartResult.charAt(i+1);
먼저 숫자를 읽는다.
1S 2D 10S
이때 10 처리를 위해 다음 문자가 숫자인지 검사한다.
if(Character.isDigit(c2)){ convert += c2; i++; }
예
1 0 S
이 경우
convert = "10"
이 된다.

점수 변환

int score = Integer.parseInt(convert);
문자열을 실제 숫자로 변환한다.

5. 보너스 계산 (S, D, T)

다음 문자를 읽어 보너스를 계산한다.
char c3 = dartResult.charAt(i+1);
보너스 종류
S → 1제곱 D → 2제곱 T → 3제곱
코드
if(bonus.equals("D")){ score*=score; } else if(bonus.equals("T")){ int origin = score; score *= origin; score *= origin; }
예
3D → 3² = 9 2T → 2³ = 8

6. 점수 배열 저장

myScore[scoreIndex] = score; scoreIndex++;
각 라운드 점수를 배열에 저장한다.
예
myScore = [1, 4, 0]

7. 옵션 처리 (*, #)

옵션은 선택 사항이기 때문에 다음 문자가 숫자인지 확인한다.
charc4=dartResult.charAt(i+2); if(!Character.isDigit(c4))
옵션 종류
옵션
의미
*
현재 + 이전 점수 2배
#
현재 점수 음수

스타 옵션 (*)

myScore[scoreIndex-1] *= 2; if(scoreIndex-1>0){ myScore[scoreIndex-2] *= 2; }
현재 점수
2배
이전 점수
있으면 같이 2배
예
1S2D* → [1,4] → [2,8]

아차 옵션 (#)

myScore[scoreIndex-1] *= -1;
현재 점수를 음수로 변경한다.

8. 최종 점수 계산

모든 라운드 계산이 끝나면 배열의 점수를 합산한다.
for(int i = 0 ; i < myScore.length ; i++){ answer += myScore[i]; }
예
[2, 8, 27]
최종 점수
37

9. 전체 알고리즘 흐름

1️⃣ 문자열을 앞에서부터 읽는다
2️⃣ 숫자를 읽어 기본 점수를 만든다
3️⃣ S / D / T 보너스를 적용한다
4️⃣ 배열에 점수를 저장한다
5️⃣ 옵션 (*, #)을 처리한다
6️⃣ 3개의 점수를 모두 더한다

10. 시간 복잡도

문자열 길이는 매우 작기 때문에
O(N)
선형 시간에 해결된다.
Share article