最长公共子串(2017蓝桥杯省赛)

题目描述:

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

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

 

题目分析:

本题可以定义一个二维数组 a[m][n] (m,n为两子串的长度),用于表示在长度为m的第一个字串中,与第二个字串n匹配的最长的字串疮毒

状态转移方程: 

if (s1[m - 1] == s2[m - 1]) 
  a[n][m] = a[n - 1][m - 1] + 1;

 

 

代码实现:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <unordered_map>
#include <set>
#include <list>
#include <memory>
using namespace std;
const int mod = 10e9 + 7;
#define N 256

int f(const char* s1, const char* s2)
{
    int a[N][N];
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    int i, j;

    memset(a, 0, sizeof(int) * N * N);
    int max = 0;
    for (i = 1; i <= len1; i++) {
        for (j = 1; j <= len2; j++) {
            if (s1[i - 1] == s2[j - 1]) {
                a[i][j] = a[i - 1][j - 1] + 1;  //填空
                if (a[i][j] > max)
                    max = a[i][j];
            }
        }
    }
    return max;
}

int main()
{
    printf("%d\n", f("abcdkkk", "baabcdadabc"));
    return 0;
}

 

posted @ 2021-04-12 19:49  Carrout  阅读(141)  评论(0编辑  收藏  举报