最長公共子序列(Longest Common Subsequence,lcs)
阿新 • • 發佈:2018-12-30
/** * LCS演算法 * 一個序列A任意刪除若干個字元得到新序列B,則B叫做A的子序列, * 兩個序列X和Y的公共子序列中,長度最長的那個,定義為X和Y的最長公共子序列 */ public static int max(int a,int b){ return (a>b)?a:b; } public static void getLCS(String x,String y){ char[] s1=x.toCharArray(); char[] s2=y.toCharArray(); int[][] array=new int[x.length()+1][y.length()+1]; //先把第一行和第一列填上零 for (int i = 0; i < array[0].length; i++) { array[0][i]=0; } for (int i = 0; i < array.length; i++) { array[i][0]=0; } //使用動態規劃的方式填入資料 for (int i = 1; i < array.length; i++) { for (int j = 1; j < array[i].length; j++) { if(s1[i-1]==s2[j-1]){//如果相等,左上角加1填入 array[i][j]=array[i-1][j-1]+1; }else{ array[i][j]=max(array[i-1][j],array[i][j-1]); } } } //列印 for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]+" "); } System.out.println(); } //從後往前找到結果 Stack result=new Stack(); int i=x.length()-1; int j=y.length()-1; while((i>=0) && (j>=0)){ if(s1[i]==s2[j]){ result.push(s1[i]); i--; j--; }else{//注意陣列和String中的位置有一位差 if(array[i+1][j+1-1]>array[i+1-1][j+1]){ j--; }else{ i--; } } } System.out.println("-----"); while(!result.isEmpty()){ System.out.println(result.pop()+" "); } }