Post

[BaekJoon] 1259번 - 팰린드롬수 [Java][C++]

[BaekJoon] 1259번 - 팰린드롬수 [Java][C++]

문제 링크


1. 문제 풀이


팰린드롬수면 뒤집었을 때도 동일한 문자열이 나와야하므로 문자열을 뒤집어서 원본 문자열과 동일한지 비교하는 방식으로 해결했다.


2. 코드


1. 풀이 [Java]

StringBuilderreverse 메서드를 활용해 주어진 문자열을 뒤집은 문자열을 생성한 후 원본 문자열과 같은지 비교하는 방식으로 해결했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;

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

        while (true) {
            String str = br.readLine();
            if (str.equals("0")) break;

            if (str.equals(new StringBuilder(str).reverse().toString())) {
                bw.write("yes\n");
            } else {
                bw.write("no\n");
            }
        }

        bw.flush();
    }
}


2. 풀이 [C++]

string에서 이터레이터를 받는 생성자를 통해 뒤집은 문자열을 생성한 후 원본 문자열과 일치하는지 비교하는 방식으로 해결했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while (true) {
        string s;
        cin >> s;

        if (s == "0") break;

        if (s == string(s.rbegin(), s.rend())) {
            cout << "yes\n";
        } else {
            cout << "no\n";
        }
    }
}

This post is licensed under CC BY 4.0 by the author.