Palindrome
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 18744 | Accepted: 6317 |
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.
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
5
Ab3bd
Sample Output
2
- package pKU_acm;
- import java.util.Scanner;
- public class PKU_1159 {
- /**
- * @param args
- * 刚开始的时候在左游标=右游标-1的时候直接将最优值返回为1了
- * 这种解决的办法在递归时能够减小递归规模,相当于剪枝
- * 但是没有考虑左游标的字符=右游标的字符,这时候应该返回0
- * 但是这种判断方法在将递归改为循环后,没有必要了
- * 因为都是通过m[][]表来计算相应的值
- *
- * 值得庆祝,这一题终于AC过关,
- */
- public static void main(String[] args) throws Exception{
- Scanner cin=new Scanner(System.in);
- cin.nextInt();
- String ch=cin.next();
- System.out.println(findMiniNum(ch));
- }
- public static int findMiniNum(String ch){
- int n=ch.length();
- short[][] m=new short[n][n];
- for(int i=n-2;i>=0;i--){
- for(int j=i+1;j<=n-1;j++){
- if(j==i+1){ //加上这一个分支语句,4016MS,去掉这个语句 3750MS。建议不要多此一举了
- if(ch.charAt(i)==ch.charAt(j))
- m[i][j]=0;
- else
- m[i][j]=1;
- }
- else if(ch.charAt(i)==ch.charAt(j)){
- m[i][j]=m[i+1][j-1];
- }else{
- m[i][j]=(short)(min(m[i+1][j],m[i][j-1])+1);
- }
- }
- }
- return m[0][n-1];
- }
- public static short min(short a,short b){
- return a<b?a:b;
- }
- }