[最长公共子序列+滚动数组优化]Palindrome

原题链接
题目让求增添几个字符是字符串是回文字符串,回文字符串还可以是字符串与其逆序字符串相等;这种想法想下去,我们可以把字符串和他的逆序字符串放成两排;使更多的一样的字符对齐,我们就把一样的先对齐然后空位就是我们需要增添的字符的个数;这就是求原字符串和他逆序字符串的最长公共子序列然后用原长减去最长公共子序列长度就是答案;
因为数据为5000;所以要用到滚动数组进行优化;

//package Problem;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        //int[] array=new int[n+5];
        String s1=scanner.next();
        char[] ch1=s1.toCharArray();
        //System.out.println(s);
        char[] ch2=new char[n+5];
        for (int i = 0; i < ch1.length; i++) {
            ch2[i]=ch1[ch1.length-1-i];
        }
        int len=ch1.length;
        int[][] dp=new int[3][n+5];
        int e=0;//滚动数组优化;
        for (int i=0;i<len;i++){
            e=1-e;
            for(int j=0;j<len;j++){
                if(ch1[i]==ch2[j]){
                    dp[e][j+1]=dp[1-e][j]+1;
                }
                else{
                    if(dp[e][j]>dp[1-e][j+1]){
                        dp[e][j+1]=dp[e][j];
                    }
                    else{
                        dp[e][j+1]=dp[1-e][j+1];
                    }
                }
            }
        }
        System.out.println(n-dp[e][n]);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44833767/article/details/104163829