Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 最长回文子序列算法,时间分析_Java_Algorithm_Dynamic Programming - Fatal编程技术网

Java 最长回文子序列算法,时间分析

Java 最长回文子序列算法,时间分析,java,algorithm,dynamic-programming,Java,Algorithm,Dynamic Programming,从本网站下载代码: /** * To find longest palindrome sub-sequence * It has time complexity O(N^2) * * @param source * @return String */ public static String getLongestPalindromicSubSequence(String source){ int n = source.length(); int[][] LP = new in

从本网站下载代码:

/**
* To find  longest palindrome sub-sequence
* It has time complexity O(N^2)
* 
* @param source
* @return String
*/
public static String getLongestPalindromicSubSequence(String source){
    int n = source.length();
    int[][] LP = new int[n][n];

    //All sub strings with single character will be a plindrome of size 1
    for(int i=0; i < n; i++){
        LP[i][i] = 1;
    }
    //Here gap represents gap between i and j.
    for(int gap=1;gap<n;gap++){
        for(int i=0;i<n-gap;i++ ){
                    int j=i+gap;
                    if(source.charAt(i)==source.charAt(j) && gap==1)
                        LP[i][j]=2;
                    else if(source.charAt(i)==source.charAt(j))
                        LP[i][j]=LP[i+1][j-1]+2;
                    else
                        LP[i][j]= Math.max(LP[i][j-1], LP[i+1][j]);              
         }      
    }   
    //Rebuilding string from LP matrix
    StringBuffer strBuff = new StringBuffer();
    int x = 0;
    int y = n-1;
    while(x < y){
        if(source.charAt(x) == source.charAt(y)){
            strBuff.append(source.charAt(x));
            x++;
            y--;
        } else if(LP[x][y-1] > LP[x+1][y]){
            y--;
        } else {
            x++;
        }
    }
    StringBuffer strBuffCopy = new StringBuffer(strBuff);
    String str = strBuffCopy.reverse().toString();
    if(x == y){          
        strBuff.append(source.charAt(x)).append(str);
    } else {
        strBuff.append(str);
    }
    return strBuff.toString();
}

public static void main(String[] args) {
    //System.out.println(getLongestPalindromicSubSequenceSize("XAYBZA"));
    System.out.println(getLongestPalindromicSubSequence("XAYBZBA"));
}
/**
*寻找最长回文子序列
*它的时间复杂度为O(N^2)
* 
*@param源
*@返回字符串
*/
公共静态字符串getLongestPalindromicSubSequence(字符串源){
int n=source.length();
int[]LP=新的int[n][n];
//所有具有单个字符的子字符串都将是大小为1的plindrome
对于(int i=0;i对于(int gap=1;gap执行内部循环体的次数为