牛客網 Coincidence(最長公共子串LCS板題)

sunlanchang發表於2019-01-28

Description

給定兩個字串,輸出最長公共子串。

Input

abcd
cxbydz

Output

2

Solution

最長公共子串板題。狀態轉移方程如下:
dp[0][j]=0 if 0jmdp[i][0]=0 if 0in,dp[i][j]=dp[i1][j1]+1 if S1[i]==S2[j]dp[i][j]=max(dp[i1][j],dp[i][j1]) if S1[i]S2[j] dp [ 0 ][ j ]=0 \ if \ 0 ≤ j ≤ m \\ dp [ i ][ 0 ]= 0 \ if \ 0 ≤ i ≤ n,\\ dp [ i ][ j ] = dp [ i − 1 ][ j − 1 ] + 1\ if\ S 1 [ i ] == S 2 [ j ] \\ dp [ i ][ j ] = max(dp [ i − 1 ][ j ], dp [ i ][ j − 1 ]) \ if \ S 1 [ i ] ≠ S 2 [ j ]

#include <cstdio>
#include <iostream>
#include <cstring>
int dp[101][101];
using namespace std;
int main()
{
    char S1[101], S2[101];
    while (scanf("%s%s", S1, S2) != EOF)
    { //輸入
        int L1 = strlen(S1);
        int L2 = strlen(S2); //依次求得兩個字串的長度
        for (int i = 0; i <= L1; i++)
            dp[i][0] = 0;
        for (int j = 0; j <= L2; j++)
            dp[0][j] = 0; //初始值
        //二重迴圈依次求得每個dp[i][j]值
        for (int i = 1; i <= L1; i++)
        {
            for (int j = 1; j <= L2; j++)
            {
                //因為字串陣列下標從0開始,所以第i個字元位置為S1[i - 1], 若當前兩個字元不相等
                if (S1[i - 1] != S2[j - 1])
                    //dp[i][j]為dp[i][j - 1] 和 dp[i - 1][j] 中較大的一個
                    dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
                else
                    //若它們相等,則dp[i][j]比dp[i - 1][j - 1] 再加一
                    dp[i][j] = dp[i - 1][j - 1] + 1;
            }
        }
        printf("%d\n", dp[L1][L2]); //輸出答案
    }
    return 0;
}

相關文章