参考出处:原始链接 和 从这篇博客发现了前面的链接(两个链接关于该题目的内容都是一样的)
题目大意
D
e
s
c
r
i
p
t
i
o
n
\color{blue}{Description}
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.
I
n
p
u
t
\color{blue}{Input}
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.
O
u
t
p
u
t
\color{blue}{Output}
Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
中
文
解
释
\color{blue}{中文解释}
中文解释
无
分析
设 **原序列S的逆序列为S’,**则这道题目的关键在于:
最少需要补充的字母数 = 原序列S的长度 — S和S’的最长公共子串长度
- 算法:LCS
- LCS图解算法
1、 阵列开始均为空
2、 S1[i]=S2[j] 相同,dp[i][j] 则继承左上方向 dp[i-1][j-1] 的值 +1
3、 不相同 dp[i][j] 则继承 上方与左方中的最大数值
代码
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner in=new Scanner(System.in);
int [][]dp=new int [2][5010];
int n;
while(in.hasNext()) {
n=in.nextInt();
char []s=(" "+in.next()).toCharArray();
Arrays.fill(dp[0], 0);
Arrays.fill(dp[1], 0);
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if(s[i]==s[n+1-j]) {
dp[i&1][j]=dp[(i-1)&1][j-1]+1;
}else {
dp[i&1][j]=Math.max(dp[(i-1)&1][j], dp[i&1][j-1]);
}
}
}
int ans=0;
for(int i=1;i<=n;i++) {
if(dp[n&1][i]>ans) ans=dp[n&1][i];
}
System.out.println(n-ans);
}
}
}
/*
5
Ab3bd
2
*/