자바 10988번

소만이·2023년 12월 15일

자바 백준문제

목록 보기
2/4

이 문제를 봤을 때 단어를 전체 다 바꾸면 되겠구나! 생각이 들었다.
예시에 나와있는 level로 설명하자면 0번 인덱스인 l과 4번 인덱스인 l, 1번 인덱스인 e와 3번 인덱스인 e 이렇게 말이다.

그래서 나온 코드는 다음과 같다.

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String word = br.readLine();
        char[] words = word.toCharArray();
        for(int i = 0; i < word.length(); i++){
            if(i == words.length-i) break;
            char temp = words[i];
            words[i] = words[words.length-i-1];
            words[words.length-i-1] = temp;

        }
        String changeWord = new String(words);

        if(word.equals(changeWord)){
            System.out.println(1);
        }else{
            System.out.println(0);
        }
    }

입력받은 word를 배열 형태로 만든 후 바꾼 것이다.
출력은 제대로 됐는데 왜인지 모르게 제출을 하면 바로 틀렸습니다가 나와서
너무 또 복잡하게 생각을 했나.. 고민을 하다가
굳이 단어를 다 바꿔서 그걸 비교할 필요 없이 0번과 4번이 같은지, 확인하면 되겠구나 라는 생각이 들었다!

아래는 이 생각으로 수정한 코드이다.

    import java.io.*;

    public class Main {
   
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String word = br.readLine();

            int check = 1;
            for(int i = 0; i < word.length(); i++){
                if (word.charAt(i) == word.charAt(word.length() - 1 - i)) {
                    check = 1;
                }else{
                    check = 0;
                    break;
                }
            }
            System.out.println(check);


        }
    }

check가 0이 되는 순간 break를 걸어 이 단어가 앞뒤가 똑같은 단어인지 파악할 수 있게 수정하였다.
이전보다 훨씬 더 보기 좋게 코드를 수정한 것 같다!
결과는 성공이었다!

++++++++++++++++++++++++++++++++++++++++++

public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String word = br.readLine();
            char[] words = word.toCharArray();
            for (int i = 0; i < word.length(); i++) {
                **if (i == words.length - i - 1) break;**
                if (i == words.length - i) break;
                char temp = words[i];
                words[i] = words[words.length - i - 1];
                words[words.length - i - 1] = temp;

            }
            String changeWord = new String(words);

            if (word.equals(changeWord)) {
                System.out.println(1);
            } else {
                System.out.println(0);
            }

위에 안됐다고 한 코드에서
if (i == words.length - i - 1) break;
이 코드를 추가했더니 성공했다!!
abc 를 예시로 들 때 1번 인덱스가 words.length-i-1과 같을 때는 바꿔줄 필요가 없기 때문에 break문을 추가했어야 했는데 이걸 간과했던 것 같다!!
그렇지만 두번째 수정한 코드가 더 보기 좋기 때문에 어쨌든 좋은 결과 과정이었다고 생각된다!

0개의 댓글