Palindrome
Description A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. Input Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
Output Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
Sample Input
Sample Output
Source |
卡內存,可以開 short 數組以節省空間。
// Version 1
#include <iostream>
#include <cstdio>
using namespace std;
short getLcs(const string& a, const string& b)
{
size_t n = a.length(), m = b.length();
short** dp = new short*[n + 1];
for (int i = 0; i <= n; i++)
{
dp[i] = new short[m + 1];
for (int j = 0; j <= m; j++) dp[i][j] = 0;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = a[i - 1] == b[j - 1] ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]);
return dp[n][m];
}
int main()
{
int n;
cin >> n;
string a;
cin >> a;
string b(a.rbegin(), a.rend());
cout << a.length() - getLcs(a, b) << endl;
return 0;
}
可以使用滾動數組節省空間。
// Version 2
#include <iostream>
#include <cstdio>
using namespace std;
int getLcs(const string& a, const string& b)
{
size_t n = a.length(), m = b.length();
int** dp = new int*[2];
for (int i = 0; i < 2; i++)
{
dp[i] = new int[m + 1];
for (int j = 0; j <= m; j++) dp[i][j] = 0;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i & 1][j] = a[i - 1] == b[j - 1] ? dp[(i + 1) & 1][j - 1] + 1 : max(dp[(i + 1) & 1][j], dp[i & 1][j - 1]);
return dp[n & 1][m];
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
int n;
cin >> n;
string a;
cin >> a;
string b(a.rbegin(), a.rend());
cout << a.length() - getLcs(a, b) << endl;
return 0;
}