[ 백준 ] 10942 팰린드롬?

codesver·2023년 3월 7일
0

Baekjoon

목록 보기
44/72
post-thumbnail

Link | 백준 10942번 문제 : 팰린드롬?

📌 About

팰린드롬이란 좌우대칭인 것을 말한다.

예를 들어 1221은 좌우 대칭이지만 1222는 좌우 대칭이 아니다.

팰린드롬인지는 양끝부터 비교하면서 확인할 수 있다.

이번 문제에서는 숫자들과 범위들이 주어졌을 때 각 범위별 팰린드롬 여부를 반환하면 된다.

📌 Solution

팰린드롬 여부를 저장하기 위해 int[][] 배열을 사용한다.

주어진 범위들을 팰린드롬 확인 함수를 통해 팰린드롬 여부를 확인한다.

만약 팰린드롬이면 그 사이의 값들도 순차적으로 팰린드롬이다.

예를 들어 1 2 3 2 1 은 팰린드롬이다.

그러면 1 2 3 2 1 뿐만이 아니라 2 3 2 와 3 또한 팰리드롬이다.

📌 Code

GitHub Repository

public void solve() throws IOException {
    int N = Integer.parseInt(reader.readLine());
    int[] nums = Arrays.stream(("0 " + reader.readLine()).split(" "))
            .mapToInt(Integer::parseInt).toArray();
    int[][] palindrome = new int[N + 1][N + 1];

    StringTokenizer tokenizer;
    int Q = Integer.parseInt(reader.readLine());
    while (Q-- > 0) {
        tokenizer = new StringTokenizer(reader.readLine());
        int s = Integer.parseInt(tokenizer.nextToken());
        int e = Integer.parseInt(tokenizer.nextToken());
        if (palindrome[s][e] == 0) {
            if (palindrome(nums, s, e)) {
                result.append(1).append("\n");
                while (s <= e) {
                    palindrome[s][e] = 1;
                    s++;
                    e--;
                }
            } else {
                result.append(0).append("\n");
                palindrome[s][e] = 2;
            }
        } else result.append(palindrome[s][e] == 1 ? 1 : 0).append("\n");
    }
}

public boolean palindrome(int[] nums, int s, int e) {
    while (s < e) {
        if (nums[s] != nums[e]) return false;
        s++;
        e--;
    }
    return true;
}
profile
Hello, Devs!

0개의 댓글