最长公共子序列问题

    xiaoxiao2021-04-13  21

    最长公共子序列问题 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic Problem Description

    给定两个序列X= Input

    输入数据有多组,每组有两行 ,每行为一个长度不超过500的字符串(输入全是大写英文字母(A,Z)),表示序列X和Y。 Output

    每组输出一行,表示所求得的最长公共子序列的长度,若不存在公共子序列,则输出0。 Example Input

    ABCBDAB BDCABA Example Output

    4 Hint

    Author 代码实现:

    #include <bits/stdc++.h> using namespace std; int c[1234][1234]; int main() { int i, j; char str1[1234], str2[1234]; //此题可以将两个字符串组成一个矩阵,通过二位数组存储公共长度 while(gets(str1)) { gets(str2); int len1 = strlen(str1); int len2 = strlen(str2); for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(str1[i-1]==str2[j-1]) c[i][j] = c[i-1][j-1] + 1;//如果两个字符相等则公共部分的数组更新+1; //否则的话,取两个相邻的数字中较大的一个 else { if(c[i-1][j]>c[i][j-1]) c[i][j] = c[i-1][j]; else c[i][j] = c[i][j-1]; } } } cout<<c[len1][len2]<<endl;//输出公共部分最长的长度 } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-668930.html

    最新回复(0)