팰린드롬인지 확인하기

이윤설·2024년 2월 8일

https://www.acmicpc.net/problem/10988

제출코드(오답)


public class Main {
    public static void main(String[] args) throws IOException{
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.<i>in</i>));
            String input = br.readLine();

            char[] charArray = input.toCharArray();
            int length = charArray.length;

            int count = 0;

            if (length % 2 == 1) {
                for (int i = 0; i < (charArray.length / 2) + 1; i++) {
                    if (charArray[i] != charArray[length - i - 1]) {
                        count = 0;
                    }
                    if (charArray[i] == charArray[length - i - 1]) {
                        count = 1;
                    }
                }
            }

            if (length % 2 == 0) {
                for (int i = 0; i < charArray.length / 2; i++) {
                    if (charArray[i] != charArray[length - i - 1]) {
                        count = 0;
                    }
                    if (charArray[i] == charArray[length - i - 1]) {
                        count = 1;
                    }
                }
            }
            if (count == 0) {
                System.<i>out</i>.println("0");
            }
            if (count != 0){
                System.<i>out</i>.println("1");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

아주 더러운 코드다!

모범답안

public class Main {
    public static void main(String[] args) throws IOException{
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = br.readLine();
            
            char[] charArray = input.toCharArray();
            int length = charArray.length;
            int count = 1; // 팰린드롬이라고 가정하고 시작
            
            for (int i = 0; i < length / 2; i++) {
                if (charArray[i] != charArray[length - i - 1]) {
                    count = 0; // 팰린드롬 조건을 만족하지 않으면 count를 0으로 업데이트하고 반복문 종료
                    break;
                }
            }
            
            System.out.println(count); // count 값 출력
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

정리

1) 팰린드롬 여부를 확인할 때는 길이의 절반만큼만 반복하여 검사하면 된다.

2) 내가 작성한 방식은 하나의 짝이 동일하면 펠린드롬으로 판별해버린다.

profile
화려한 외면이 아닌 단단한 내면

0개의 댓글