SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.util.Scanner;
import java.io.FileInputStream;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++)
{
String word = sc.next();
String[] words = word.split("");
try{
validateWords(words, test_case);
validateHalfWords(words, test_case);
System.out.println("#" + test_case + " YES");
}
catch(IllegalArgumentException e){
System.out.println(e.getMessage());
}
}
}
public static void validateWords(String[] words, int test_case){
for(int i=0; i<words.length/2; i++){
if(!words[i].equals(words[words.length-i-1])){
throw new IllegalArgumentException("#" + test_case + " NO");
}
}
}
public static void validateHalfWords(String[] words, int test_case){
String[] halfWords1 = new String[words.length/2];
String[] halfWords2 = new String[words.length/2];
for(int j=0; j<words.length/2; j++){
halfWords1[j] = words[j];
halfWords2[j] = words[words.length-1-j];
}
for(int k=0; k<halfWords1.length/2; k++){
if(!halfWords1[k].equals(halfWords1[halfWords1.length-k-1])){
throw new IllegalArgumentException("#" + test_case + " NO");
}
else if(!halfWords2[k].equals(halfWords2[halfWords2.length-k-1])){
throw new IllegalArgumentException("#" + test_case + " NO");
}
}
}
}
그냥 절차적으로 쭉 쓰면 이중 포문 쓰고 break 하면서 풀 수 있겠지만, 우테코 프리코스를 진행하면서 배운 점이 많기 때문에 굳~이 메서드를 분리(전체 검증, 절반 검증)하고 예외를 던지는 식으로 풀어보기로 했다.
특이사항) 기본적으로 mian에 throws Exception이 걸려있는데 메서드 분리하는 경우 매 메서드마다 throws Exception을 걸어주고 처리해야한다. 지난 주부터 잘 배워서 써먹고있는 IllegalArgumentException의 경우에는 그럴 필요 없음 예외 처리의 방식이 다르기 때문이다.
'SWEA' 카테고리의 다른 글
[SWEA] 등차수열 만들기 (1) | 2024.11.05 |
---|---|
[SWEA] 식료품 가게 (0) | 2024.10.29 |
[SWEA] 증가하는 사탕 수열 (0) | 2024.10.25 |
[SWEA] 공평한 분배 2 (0) | 2024.10.25 |
[SWEA] 어디에 단어가 들어갈 수 있을까 (+오답) (0) | 2024.10.15 |