Expm 6_1 最长公共子序列问题

递推式如下:

 

 1 public class Exp6_1 {
 2 
 3     //LCS最长公共子序列问题
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         
 7         //最长公共子序列长度为:5
 8         //最长公共子序列为:A B C D E 
 9         String str1="ABCDEFG";
10         String str2="HAIBJCKDLEM";
11         computeLCS(str1,str2);
12         
13         
14         //最长公共子序列长度为:0
15         //最长公共子序列为:
16         System.out.println();
17         String str3="abcdefghijk";
18         String str4="lmnopqrstuv";
19         computeLCS(str3, str4);
20     }
21 
22     public static void computeLCS(String str1,String str2){
23         int[][] c=new int[str1.length()+1][str2.length()+1];
24         
25         for(int i=0;i<=str1.length();i++)
26             c[i][0]=0;
27         for(int j=0;j<=str2.length();j++)
28             c[0][j]=0;
29         
30         for(int i=0;i<str1.length();i++){
31             for(int j=0;j<str2.length();j++)
32             {
33                 String s1=str1.substring(i, i+1);
34                 String s2=str2.substring(j, j+1);
35                 if(s1.equals(s2)){
36                     c[i+1][j+1]=c[i][j]+1;
37                 }else{
38                     if(c[i+1][j]>c[i][j+1])
39                         c[i+1][j+1]=c[i+1][j];
40                     else
41                         c[i+1][j+1]=c[i][j+1];
42                 }
43             }
44         }
45         
46         System.out.println("最长公共子序列长度为:"+c[str1.length()][str2.length()]);
47         String lcs="";
48         for(int i=str1.length(),j=str2.length();i>=1&& j>=1;){
49             String s1=str1.substring(i-1, i);
50             String s2=str2.substring(j-1, j);
51             if(s1.equals(s2)){
52                 lcs=s1+" "+lcs;
53                 i--;
54                 j--;
55             }
56             else{
57                 if(c[i][j-1]>c[i-1][j])
58                 {
59                     j--;
60                 }
61                 else{
62                     i--;
63                 }                    
64             }
65         }
66         System.out.println("最长公共子序列为:"+lcs);
67     }
68     
69 
70 }
View Code

 

posted @ 2017-11-02 18:57  清风☆薰衣草  阅读(231)  评论(0)    收藏  举报