最长公共子串

http://blog.csdn.net/steven30832/article/details/8260189

Java实现:

 1 public class Main {
 2 
 3     /**
 4      * 最长公共子串
 5      *     --b  a  b
 6 
 7      *    c 0  0  0
 8 
 9      *    a 0  1  0
10 
11      *    b 1  0  2
12 
13      *    a 0  2  0
14      * @param args
15      */
16     public static void main(String[] args) {
17         char[] str1 = {'c', 'a', 'b', 'a'};
18         char[] str2 = {'c', 'a', 'b', 'a'};
19         /* 记录匹配结果 */
20         int[] c = new int[str2.length+1];
21         
22         getLCS(str1, str2, c);
23     }
24     /**
25      * 
26      * @param str1 字符序列1
27      * @param str2  字符序列1
28      * @param c 上一行匹配结果
29      */
30     public static int getLCS(char[] str1, char[] str2, int[] c){
31         
32         if (str1 == null || str2 == null ) {
33             return -1;
34         }
35         
36         for (int i = 0; i < c.length; i++) {
37             c[i] = 0;
38         }
39         
40         int max_len = 0;    //匹配的长度  
41         int pos = 0;        //在str2上的匹配最末位置  
42         for (int i = 0; i < str1.length; i++) {
43             
44             for(int j = str2.length; j >0; j--){
45                 
46                 if (str1[i] == str2[j-1]) {
47                     
48                     c[j] = c[j-1] + 1; 
49                     
50                     if(c[j] > max_len)  
51                     {  
52                         max_len = c[j];  
53                         pos = j-1;  
54                     }
55                     
56                 }else {
57                     c[j] = 0;
58                 }
59             }
60             
61         }
62         
63         /* 打印最长公共子串 */
64         for(int i = 1; i <= max_len; i++){
65             System.out.println(str2[pos-max_len+i]);
66         }
67         
68         return max_len;
69     }
70     
71 }

 

posted @ 2014-09-22 20:24  soul390  阅读(122)  评论(0)    收藏  举报