본문 바로가기

Algorithm/BAEKJOON

[BOJ] 5502번 팰린드롬 (C++)

728x90
반응형

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

 

5502번: 팰린드롬

팰린드롬이란 대칭 문자열이다. 즉, 왼쪽에서 오른쪽으로 읽었을때와 오른쪽에서 왼쪽으로 읽었을때 같다는 얘기다. 당신은 문자열이 주어졌을때, 최소 개수의 문자를 삽입하여 팰린드롬이

www.acmicpc.net

 

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

int dp[5001][5001];

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n;
	cin >> n;
	
	string s, r_s;
	cin >> s;
	r_s = s;
	reverse(r_s.begin(), r_s.end());
	
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(s[i - 1] == r_s[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
			else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
		}
	}
	
	cout << n - dp[n][n] << endl;
	
	return 0;
}

 

해당 문제는 LCS와 연관이 있다.

 

1. 입력받은 문자열과 뒤집은 문자열과의 LCS 구하기

2. N - LCS 이 정답

728x90
반응형