最长公共子序列

时间限制:65535 KB
难度:3
 
描述
咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
 
输入
第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000.
输出
每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。
样例输入
2
asdf
adfsd
123abc
abc123abc
样例输出
3
6

 

 

思路:动态规划,不是KMP!!!

 

 

 

 

 
#include <iostream>
#include <string>
#include <cstdio>
 
using namespace std;

int martix[1000][1000] = {0};

 int main(){

    int n;
    cin>>n;
    while (n--)
    {
        string a,b;
        cin>>a>>b;
        int i,j;

        for (i = 1; i <= a.length(); i++)
        {
            for (j = 1; j <= b.length(); j++)
            {
                if (a[i-1]==b[j-1])
                {
                    martix[i][j] = martix[i-1][j-1] + 1;
                }
                else
                {
                    if (martix[i][j-1] > martix[i-1][j])
                    {
                        martix[i][j] = martix[i][j-1];
                    }
                    else
                    {
                        martix[i][j] = martix[i-1][j];
                    }
                }
            }
        }
        cout<<martix[a.length()][b.length()]<<endl;
        
    }

     return 0;
 }        

 

相关文章:

  • 2021-10-16
  • 2021-12-14
  • 2021-10-11
  • 2021-07-01
  • 2022-01-02
猜你喜欢
  • 2021-07-15
  • 2022-01-16
  • 2021-06-13
  • 2021-04-26
  • 2021-09-02
相关资源
相似解决方案