※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 24832번 문제인 Longest Palindrome이다.
문제는 아래 링크를 확인하자.

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

 

24832번: Longest Palindrome

Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and

www.acmicpc.net

(1) 주어지는 문자열의 길이가 일정하고 (2) 같은 문자열은 두번 이상 주어지지 않다는 조건에 유의하자.

 

위와 같은 조건을 이용하면, 서로 뒤집어서 같은 문자열들과 자기 자신이 회문인 문자열들을 살피는 것으로 문제를 해결할 수 있다.

 

set을 이용하여 문제를 쉽게 해결하자. algorithm헤더의 reverse 함수를 이용하면 구현을 편하게 할 수 있다.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
using namespace std;

set<string> stringSet;
string ansL = "", ansM = "", ansR = "";

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

	int N, M; cin >> N >> M;
	while (N--) {
		string s; cin >> s;
		string ss = s;
		reverse(ss.begin(), ss.end());
		if (s == ss) ansM = s;
		else if (stringSet.find(ss) != stringSet.end()) {
			ansL = ansL + s, ansR = ss + ansR;
		}
		else stringSet.insert(s);
	}

	string ans = ansL + ansM + ansR;
	cout << ans.length() << '\n' << ans;
}

 

728x90

+ Recent posts