[BaekJoon] #10988 - 팰린드롬인지 확인하기 [Java][C++]
[BaekJoon] #10988 - 팰린드롬인지 확인하기 [Java][C++]
1. 아이디어
주어진 문자열의 양 끝에 포인터를 위치시킨 후 한 칸씩 이동하며 서로 가리키는 문자가 일치하는지 비교하는 방식으로 해결해도 되고, 주어진 문자열을 뒤집은 후 원본 문자열과 일치하는지 비교하는 방식으로 해결해도 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = s의 길이)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String rs = new StringBuilder(s).reverse().toString();
if (s.equals(rs)) {
System.out.println(1);
} else {
System.out.println(0);
}
}
}
StringBuilder의 reverse 메서드를 활용해 주어진 문자열을 뒤집은 문자열을 생성한 후 원본 문자열과 같은지 비교하는 방식으로 해결했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
string rs = string(s.rbegin(), s.rend());
cout << (s == rs);
}
std::string에서 이터레이터를 받는 생성자를 통해 뒤집은 문자열을 생성한 후 원본 문자열과 일치하는지 비교하는 방식으로 해결했다.
This post is licensed under CC BY 4.0 by the author.