第八届蓝桥杯省赛真题--最大公共子串

一、问题描述

  最大公共子串长度问题就是:求两个串的所有子串中能够匹配上的最大长度是多少。

  比如:"abcdkkk" 和 "baabcdadabc",可以找到的最长的公共子串是"abcd",所以最大公共子串长度为4。

  下面的程序是采用矩阵法进行求解的,这对串的规模不大的情况还是比较有效的解法。请分析该解法的思路,并补全划线部分缺失的代码。

 1 public class Main
 2 {
 3     static int f(String s1, String s2)
 4     {
 5         char[] c1 = s1.toCharArray();
 6         char[] c2 = s2.toCharArray();
 7         
 8         int[][] a = new int[c1.length+1][c2.length+1];
 9         
10         int max = 0;
11         for(int i=1; i<a.length; i++){
12             for(int j=1; j<a[i].length; j++){
13                 if(c1[i-1]==c2[j-1]) {
14                     a[i][j] = __________________;  //填空 
15                     if(a[i][j] > max) max = a[i][j];
16                 }
17             }
18         }
19         
20         return max;
21     }
22     
23     public static void main(String[] args){
24         int n = f("abcdkkk", "baabcdadabc");
25         System.out.println(n);
26     }
27 }

  注意:只提交缺少的代码,不要提交已有的代码和符号。也不要提交说明性文字。

二、题目类型:代码填空、动态规划

三、解题思路及答案

    

  答案:a[i-1][j-1] + 1

猜你喜欢

转载自www.cnblogs.com/crush-u-1214/p/10521019.html