class Solution {
public int solution(String dartResult) {
int answer = 0;
int[] scores = new int[3];
String[] data = dartResult.split("");
// 투 포인터 처럼 조건 만족하여 갱신 될때만 다루는 배열의 인덱스 조절
int idx = 0;
for(int i=0; i<data.length; i++){
// if 문 으로 조건 만족하는 문자열 검출하기 보다 matches로 검증하기
if(data[i].matches("[0-9]")){
scores[idx]+=Integer.parseInt(data[i]);
if(data[i+1].matches("[0-9]")){
scores[idx]*=10;
continue;
}
idx++;
}
else{
switch(data[i]){
case "D":
// Math.pow(int,지수) 의 반환형은 double이다.
scores[idx-1] = (int) Math.pow(scores[idx-1],2);
break;
case "T":
scores[idx-1] = (int) Math.pow(scores[idx-1],3);
break;
case "*":
scores[idx-1]*=2;
if(idx-2>=0) scores[idx-2]*=2;
break;
case "#":
scores[idx-1]*=-1;
}
}
}
for(int i=0; i<3; i++){
answer+=scores[i];
}
return answer;
}
}
2 번째 풀이
class Solution {
public int solution(String dartResult) {
int answer = 0;
int[] scores = new int[3];
String[] data = dartResult.split("");
int idx = 0;
for(int i=0; i< data.length; i++){
String cur = data[i];
if(cur.matches("[0-9]")){
if(data[i+1].matches("[0-9]")){
i++;
scores[idx++] = 10;
}else{
scores[idx++] = Integer.parseInt(cur);
}
}
else if(cur.equals("D")) scores[idx-1] *= scores[idx-1];
else if(cur.equals("T")) scores[idx-1] *= scores[idx-1]*scores[idx-1];
else if(cur.equals("*")) {
if(idx-2>=0){
scores[idx-2] *=2;
}
scores[idx-1] *=2;
} else if(cur.equals("#")) scores[idx-1] *=-1;
}
for(int i=0; i<3; i++){
answer += scores[i];
}
return answer;
}
}
문자열 비교는 equlas로 하자