1. 程式人生 > >最長公共子序列LCS

最長公共子序列LCS

chang 因此 數據 超過 ear print () 哪些 class

 1 public class Zuichangzixulie {
 2     //X[n] 取哪些
 3     //Y[m] 取哪些
 4 //    int search(int xi, int yi){
 5 //        int n ,m;
 6 //        if(xi>=n || yi>=m) return -1;
 7 //        if(xi == n && yi == m) return 0;
 8 //        return Math.max(
 9 //        if (X[xi] == Y[yi] search(xi+1, yi+1) + 1,
10 // search(xi, yi+1), 11 // search(xi+1, yi) 12 // ); 13 // 14 // } 15 public static int lcs(String a,String b){ 16 int len1 = a.length(); 17 int len2 = b.length(); 18 int c[][] = new int[len1+1][len2+1]; 19 for(int i = 1; i <= len1;i++){
20 for(int j = 1; j <= len2;j++){ 21 if(i == 0 || j == 0){c[i][j] = 0;} 22 if(a.charAt(i-1) == b.charAt(j-1)){ 23 c[i][j] = c[i-1][j-1]+1; 24 //System.out.println(c[i][j]); 25 }else{ 26 c[i][j] = Math.max(c[i-1][j],c[i][j-1]);
27 } 28 } 29 } 30 return c[len1][len2]; 31 32 33 } 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 String a = "1A2C3D4B56"; 37 String b = "B1D23CA45B6A"; 38 39 System.out.println(lcs(a, b)); 40 } 41 42 }

例題:

1、對於兩個字符串,請設計一個高效算法,求他們的最長公共子序列的長度,這裏的最長公共子序列定義為有兩個序列U1,U2,U3...Un和V1,V2,V3...Vn,其中Ui&ltUi+1,Vi&ltVi+1。且A[Ui] == B[Vi]。

給定兩個字符串A和B,同時給定兩個串的長度n和m,請返回最長公共子序列的長度。保證兩串長度均小於等於300。

測試樣例:
"1A2C3D4B56",10,"B1D23CA45B6A",12
返回:6

2、

我們有兩個字符串m和n,如果它們的子串a和b內容相同,則稱a和b是m和n的公共子序列。子串中的字符不一定在原字符串中連續。
例如字符串“abcfbc”和“abfcab”,其中“abc”同時出現在兩個字符串中,因此“abc”是它們的公共子序列。此外,“ab”、“af”等都是它們的字串。
現在給你兩個任意字符串(不包含空格),請幫忙計算它們的最長公共子序列的長度。

輸入描述:

輸入包含多組數據。

每組數據包含兩個字符串m和n,它們僅包含字母,並且長度不超過1024。

輸出描述:

對應每組輸入,輸出最長公共子序列的長度。
示例1

輸入

abcfbc abfcab
programming contest
abcd mnp

輸出

4
2
0
 1 import java.util.Scanner;
 2 public class ZuichangLCS {
 3     public static int lcs(String a,int n,String b, int m){
 4         n = a.length();
 5         m = b.length();
 6         int c[][] = new int[n+1][m+1];
 7         for(int i = 1; i <= n;i++){
 8             for(int j = 1; j <= m;j++){
 9                 if(i == 0 || j == 0){c[i][j] = 0;}
10                  if(a.charAt(i-1) == b.charAt(j-1)){
11                     c[i][j] = c[i-1][j-1]+1;
12                     //System.out.println(c[i][j]);
13                 }else{
14                     c[i][j] = Math.max(c[i-1][j],c[i][j-1]);
15                 }
16             }
17         }
18         return c[n][m];
19         
20         
21     }
22     public static void main(String[] args) {
23         // TODO Auto-generated method stub
24         Scanner sc = new Scanner(System.in);
25         while(sc.hasNext()){
26             String a = sc.next();
27             String b = sc.next();
28             System.out.println(lcs(a,a.length(),b,b.length()));
29         }
30     }
31 
32 }





最長公共子序列LCS