雅虎笔试题-最大公共子串

给定字符串A和B,输出A和B中的最大公共子串。
比如A="aocdfe" B="pmcdfa" 则输出"cdf"

首先想到的方法,自然是

1、取出较短字符串B, 查看是否是较长字符串A的子串,如果 是,则成功返回,最大子串为B

2、否则, 依次减少长度,查看sub(B, i, i+k)是否是A的子串,是,则返回,否则继续减小长度,直到为0

 

第二种方法,是基于如下的观察:

B A  a o c    d    f    e

p     0   0   0   0   0    0

m    0   0   0   0   0    0

c     0   0   1   0   0    0

d     0   0   0   2   0   0

f     0   0    0   0   3   0

a     0  0    0   0    0   0

A[2] = B[2], 此时 flag[1][1] = 0, flag[2][2] = flag[1][1] +1 

这样便可以添加辅助数组,利用动态规划,求出

 

void GetMaxString(char ch1[], char ch2[])
{
  int arr[20];
  int max0 = 0, max1 = 0, pos = -1;
  int len1 = strlen(ch1);
  int len2 = strlen(ch2);
  for(int i=0; i<20; i++) arr[i] = 0;
  for(int i=1; i<len1; i++){
    for(int j=len2-1; j>0; j--){
      if(ch2[j] == ch1[i]){
        arr[j] = arr[j-1]+1;
        cout << arr[j] << " ";
        if(arr[j] > max1){
          max1 = arr[j];
          if(max1 > max0){
            max0 = max1;
            pos = j;
          }
        }
      }
      else arr[j] = 0;
    }
  }
  cout << "pos:"<< pos << " max:" << max0 << endl;

}

 

 

posted @ 2012-09-27 21:11  blong2010  阅读(320)  评论(0编辑  收藏  举报