문제 설명
https://school.programmers.co.kr/learn/courses/30/lessons/17682


제한 사항

입출력 예

풀이
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Solution {
public int solution(String dartResult) {
Matcher mat = Pattern.compile("[0-9]+(S|D|T)(\\*|\\#)?").matcher(dartResult);
int[] answer = new int[3];
int count = 0;
while(mat.find()) {
String s = mat.group();
Matcher m = Pattern.compile("[0-9]+|(S|D|T)|(\\*|\\#)?").matcher(s);
int result1 = Integer.parseInt(m.group());
String result2 = m.group();
answer[count] = (int) Math.pow(result1, (result2.equals("S") ? 1 : (result2.equals("D") ? 2 : 3)));
if (m.find()) {
int temp = m.group().equals("*") ? 2 : -1;
answer[count] *= temp;
if (count > 0 && temp == 2) answer[count - 1] *= temp;
}
count++;
}
return answer[0] + answer[1] + answer[2];
}
}
ㄴ 처음에 생각했던 코드 (미완성)
import java.util.Map;
class Solution {
public int solution(String dartResult) {
Map<Character, Integer> bonusMap = Map.of('S', 1, 'D', 2, 'T', 3, '*', 2, '#', -1);
String[] scoreStr = dartResult.split("[SDT*#]+"); // 숫자만 추출
int[] score = new int[3];
String[] bonus;
dartResult = dartResult.replaceFirst("\\d+", ""); // 맨 앞 숫자 제거
bonus = dartResult.split("\\d+"); // 숫자를 제외한 나머지 문자열 추출
for (int i = 0; i < 3; i++) {
score[i] = Integer.parseInt(scoreStr[i]);
score[i] = (int) Math.pow(score[i], bonusMap.get(bonus[i].charAt(0))); // S, D, T 적용
if (bonus[i].length() == 2) { // *, # 있는 경우
score[i] *= bonusMap.get(bonus[i].charAt(1));
if (i > 0 && bonus[i].charAt(1) == '*') score[i - 1] *= bonusMap.get(bonus[i].charAt(1));
}
}
return score[0] + score[1] + score[2];
}
}
ㄴ 최종 제출 코드
후기
문자열을 숫자와 영문자, 특수문자로 잘 나눌 수 있는지 확인하는 문제이다. 처음에는 Pattern과 Matcher를 사용해서 풀려고 했다. 사실 이 클래스들을 처음 알아서 찾아보긴 했었는데 find()와 group() 메서드를 사용하려니까 뭔가 알아보기 편하지가 않아서 그냥 쉬운 쪽으로 풀기로 했다. 최종적으로 작성한 코드는 숫자를 먼저 분리하여 따로 보관하고 dartResult에서 맨 앞 숫자를 제거한다. 제거하지 않으면 나중에 split()으로 나눌 때 빈 배열이 맨 앞에 하나 생긴다. 그 후에는 숫자를 제외한 문자열들을 추출하고 차례대로 S, D, T와 *, #을 적용시키면 된다.
'코딩테스트 (프로그래머스) > Java' 카테고리의 다른 글
| [프로그래머스][JAVA][Lv. 1] 예산 (0) | 2023.07.23 |
|---|---|
| [프로그래머스][JAVA][Lv. 1] [1차] 비밀지도 (0) | 2023.07.22 |
| [프로그래머스][JAVA][Lv. 1] 완주하지 못한 선수 (0) | 2023.07.20 |
| [프로그래머스][JAVA][Lv. 1] K번째수 (0) | 2023.07.19 |
| [프로그래머스][JAVA][Lv. 1] 기사단원의 무기 (0) | 2023.07.18 |