本文主要是介绍杭电1513(Palindrome),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
点击打开杭电1513
Problem Description
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
Output
Sample Input
5 Ab3bd
Sample Output
2
题意:
给出一个字符串,问让此字符串变成一个回文串最少要加多少个字符
思路:
将此字符串倒序所得的字符串与本身进行lcs,用n减去所求的最长公共子序列的长度就是答案
代码:
import java.util.*;
class P1513{static String str;static char[] str1;static char[] str2;static int n;static int[][] dp;public static void main(String[] args){Scanner sc=new Scanner(System.in);while(sc.hasNext()){n=sc.nextInt();str2=new char[n];str1=new char[n];str=sc.next();str1=str.toCharArray();for(int i=0;i<n;i++){str2[i]=str1[n-i-1];}lcs();System.out.println(n-dp[n%2][n]);}}public static void lcs(){int i,j;dp=new int[n+1][n+1];for(i=1;i<=n;i++){for(j=1;j<=n;j++){int x=i%2;int y=1-x;if(str1[i-1]==str2[j-1]){dp[x][j]=dp[y][j-1]+1;}else{dp[x][j]=Math.max(dp[y][j], dp[x][j-1]);}}}}
}
这篇关于杭电1513(Palindrome)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!