wyyy721 发表于 2017-7-10 11:26:41

华为OJ之最长公共子串

  题目描述:
  对于两个给定的字符串,给出他们的最长公共子串。
  题目分析:
  1,最长公共子串(LCS)实际上是最长公共子序列的一种特殊情况,相当于是求连续的最长子序列。我们今天先解决这个特殊情况,后续博文会探讨一般化的子序列问题;
  2,对于本题,仍然可以通过穷举法来解,一个长度为n的字符串的连续非空子串共有n * (n + 1) / 2个(为什么?),我们可以选取其中较短的一个字符串来取样本子串依次检查。但是穷举法往往是我们在没有其他更好的办法时的最后选择,对于LCS我们先尝试用动态规划的知识来解决;
  3,我们假设输入为str1, str2,
  3-1,构建一个二维数组temp,维度依次为(str1.length + 1), (str2.length + 1)。
  3-2,temp的含义:同时以str1.charAt(i - 1)和str2.charAt(j - 1)结尾的最长公共子串(注意理解这个数组的含义)的长度,例如对于str1 =="yonguo", str2 == "yonggguo", temp == 4("yong"), 而temp == 0, temp == 1("g");
  3-3,显然temp == 0, i == 0 || j == 0;
  3-4,否则,当 str1.charAt(i - 1) == str2.charAt(j - 1)时,temp = temp + 1, 否则temp == 0;
  4,如果还有其它更好的想法,欢迎大家与我交流^-^
  具体代码(Java实现):



import java.util.Scanner;

public class LCS {
   public static void main(String args[]) {
         String str1 = getInput();
         String str2 = getInput();
         System.out.println(getMaxSubString(str1, str2));
   }

   public static String getMaxSubString(String str1, String str2) {
         int length = 0;
         int index1 = 0;
         int index2 = 0;
         int[][] temp = new int;
         for (int i = 0; i <= str1.length(); i++) {
             for (int j = 0; j <= str2.length(); j++) {
               if (i == 0 || j == 0) {
                     // initialization...
                     temp = 0;
               } else {
                     // iterate and record the maximum length.
                     temp = (str1.charAt(i - 1) == str2.charAt(j - 1)) ? (temp + 1) : 0;
                     if (temp > length) {
                         length = temp;
                         index1 = i - 1;
                         index2 = j - 1;
                     }
               }
             }
         }
         if (length == 0) {
             return "";
         } else {
             StringBuffer subString = new StringBuffer();
             while (true) {
               if (index1 >= 0 && index2 >= 0 && (str1.charAt(index1) == str2.charAt(index2))) {
                     subString.append(str1.charAt(index1));
                     index1--;
                     index2--;
               } else {
                     break;
               }
             }
             return subString.reverse().toString();
         }
   }

   public static String getInput() {
         @SuppressWarnings("resource")
         Scanner reader = new Scanner(System.in);
         return reader.nextLine();
   }
}
页: [1]
查看完整版本: 华为OJ之最长公共子串