构造回文(动态规划,递归算法)

给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。

输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.

对于每组数据,输出一个整数,代表最少需要删除的字符个数。

输入例子:

abcda
google

输出例子:

2

2

import java.io.*;
import java.util.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()) {
            String s = in.nextLine();
            StringBuilder sb = new StringBuilder(s);
            sb.reverse();
            char x[] = s.toCharArray();
	        char y[] = sb.toString().toCharArray();
		    sb = getStringsLCS(x,y);
            System.out.println(s.length() - sb.length());
        }

	}
	
	public static StringBuilder getStringsLCS(char []x, char[] y) {
	    int m = x.length;
	    int n = y.length;
	    int [][] c = new int[m + 1][n + 1];
	    int [][] b = new int[m + 1][n + 1];
	    
	    for(int i = 0;i <= m; i++) {
	        c[i][0] = 0;
	    }
	    for(int i = 0;i <= n; i++) {
	        c[0][i] = 0;
	    }
	    
	    for(int i = 0;i < m; i++) {
	        for(int j = 0;j < n; j++) {
	            if(x[i] == y[j]) {
	                c[i + 1][j + 1] = c[i][j] + 1;
	                b[i + 1][j + 1] = 0;
	            }
	            else if(c[i + 1][j] >= c[i][j + 1]) {
	                c[i + 1][j + 1] = c[i + 1][j];
	                b[i + 1][j + 1] = 1;
	            }
	            else {
	                c[i + 1][j + 1] = c[i][j + 1];
	                b[i + 1][j + 1] = 2;
	            }
	        }
	    }
	    
	    //printArray2D(b);
	    return outputStringsLCS(b,x,m,n);
	}
	
	static void printArray2D(int[][] c) {
	    for(int i = 0;i < c.length;i ++) {
	        for(int j = 0;j < c[0].length;j ++) {
	            System.out.print(c[i][j]);
	        }
	        System.out.println("");
	    }
	}
	
	static StringBuilder outputStringsLCS(int[][] b,char[] x, int i, int j) {
	    if(i == 0 || j == 0) {
	        return new StringBuilder();
	    }
	    
	    StringBuilder sb;
	    
	    if(b[i][j] == 0) {
	        sb = outputStringsLCS(b, x, i - 1, j - 1);
	        sb.append(x[i - 1]);
	    }
	    else if(b[i][j] == 1) {
	        return outputStringsLCS(b, x, i, j - 1);
	    }
	    else {
	        return outputStringsLCS(b, x, i - 1, j);
	    }
	    return sb;
	}
}

    原文作者:递归算法
    原文地址: https://blog.csdn.net/hhdsyxwei/article/details/51685505
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞