博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

华为OJ之最长公共子串

Posted on 2017-04-14 23:06  Yonguos  阅读(548)  评论(0编辑  收藏  举报

题目描述:

对于两个给定的字符串,给出他们的最长公共子串。

题目分析:

1,最长公共子串(LCS)实际上是最长公共子序列的一种特殊情况,相当于是求连续的最长子序列。我们今天先解决这个特殊情况,后续博文会探讨一般化的子序列问题;

2,对于本题,仍然可以通过穷举法来解,一个长度为n的字符串的连续非空子串共有n * (n + 1) / 2个(为什么?),我们可以选取其中较短的一个字符串来取样本子串依次检查。但是穷举法往往是我们在没有其他更好的办法时的最后选择,对于LCS我们先尝试用动态规划的知识来解决;

3,我们假设输入为str1, str2,

   3-1,构建一个二维数组temp,维度依次为(str1.length + 1), (str2.length + 1)。

     3-2,temp[i][j]的含义:同时以str1.charAt(i - 1)和str2.charAt(j - 1)结尾的最长公共子串(注意理解这个数组的含义)的长度,例如对于str1 =="yonguo", str2 == "yonggguo", temp[4][4] == 4("yong"), 而temp[5][5] == 0, temp[4][5] == 1("g");

     3-3,显然temp[i][j] == 0, i == 0 || j == 0;

     3-4,否则,当 str1.charAt(i - 1) == str2.charAt(j - 1)时,temp[i][j] = temp[i - 1][j - 1] + 1, 否则temp[i][j] == 0;

4,如果还有其它更好的想法,欢迎大家与我交流^-^

具体代码(Java实现):

 1 import java.util.Scanner;
 2 
 3 public class LCS {
 4     public static void main(String args[]) {
 5         String str1 = getInput();
 6         String str2 = getInput();
 7         System.out.println(getMaxSubString(str1, str2));
 8     }
 9 
10     public static String getMaxSubString(String str1, String str2) {
11         int length = 0;
12         int index1 = 0;
13         int index2 = 0;
14         int[][] temp = new int[str1.length() + 1][str2.length() + 1];
15         for (int i = 0; i <= str1.length(); i++) {
16             for (int j = 0; j <= str2.length(); j++) {
17                 if (i == 0 || j == 0) {
18                     // initialization...
19                     temp[i][j] = 0;
20                 } else {
21                     // iterate and record the maximum length.
22                     temp[i][j] = (str1.charAt(i - 1) == str2.charAt(j - 1)) ? (temp[i - 1][j - 1] + 1) : 0;
23                     if (temp[i][j] > length) {
24                         length = temp[i][j];
25                         index1 = i - 1;
26                         index2 = j - 1;
27                     }
28                 }
29             }
30         }
31         if (length == 0) {
32             return "";
33         } else {
34             StringBuffer subString = new StringBuffer();
35             while (true) {
36                 if (index1 >= 0 && index2 >= 0 && (str1.charAt(index1) == str2.charAt(index2))) {
37                     subString.append(str1.charAt(index1));
38                     index1--;
39                     index2--;
40                 } else {
41                     break;
42                 }
43             }
44             return subString.reverse().toString();
45         }
46     }
47 
48     public static String getInput() {
49         @SuppressWarnings("resource")
50         Scanner reader = new Scanner(System.in);
51         return reader.nextLine();
52     }
53 }