package base;

import java.util.LinkedList;
import java.util.List;

//O(mn)动态规划求最长公共子序列 
public class MaxSeq {
    
    private static String str = "aebae";  //为了方便直接用自身和自身的逆序 m=n
    private int strSize = str.length();
    
    public static void main(String[] args) {
        
        MaxSeq pr = new MaxSeq();
        int strSize = str.length();
        int[][] maxArray = new int[strSize+1][strSize+1];;
        pr.buildMaxArray(maxArray, str);
        System.out.println("The One of MaxSeqs For this String is = " + pr.getMaxMaxSeq(maxArray, str));
    }
    
    private void buildMaxArray(int[][] maxArray,String str){
        
        char[] array = str.toCharArray();
        char[] array2 = new StringBuilder(str).reverse().toString().toCharArray();
        
        for(int i=1;i<strSize+1;i++){
            for(int j=1;j<strSize+1;j++){
                if(array2[i-1] == array[j-1]){
                    maxArray[i][j] = maxArray[i-1][j-1]+1;
                }else 
                    maxArray[i][j] = Math.max(maxArray[i-1][j], maxArray[i][j-1]);
            }
        }
    }
    
    private String getMaxMaxSeq(int[][] maxArray,String str){
        
        char[] array = str.toCharArray();
        char[] array2 = new StringBuilder(str).reverse().toString().toCharArray();
        int i = strSize;
        int j = strSize;
        List<Character> resultList = new LinkedList<Character>();
        while(i>0 && j>0){
            if(array[j-1] == array2[i-1]){
                resultList.add(array[j-1]);
                i--;
                j--;
            }else{
                if(maxArray[i][j-1] >= maxArray[i-1][j]){
                    j--;
                }else{
                    i--;
                }
            }
        }
        return resultList.toString();
    }
}

注意:最长公共自序列是可以不连续的,而最长公共子串必须是连续的。

posted on 2012-04-22 15:53  真心的不懂  阅读(285)  评论(0编辑  收藏  举报