题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:
abcd
cxbydz
样例输出:
2

#include <iostream>
using namespace std;

char a[100],b[100];
int t[100];
int la,lb;

int getMax(int a,int b,int c){
    int d = a>b?a:b;
    return d>c?d:c;
}

int getLCS(){
    la = strlen(a);
    lb = strlen(b);
    int m[la+1][lb+1];
    for(int i=0;i<la+1;i++){
        m[i][0] = 0;
    }
    for(int i=0;i<lb+1;i++){
        m[0][i] = 0;
    }
    for(int i=1;i<la+1;i++){
        for(int j=1;j<lb+1;j++){
            if(a[i-1]==b[j-1]){
                m[i][j]=getMax(m[i-1][j],m[i][j-1],m[i-1][j-1]+1);
            }
            else{
                m[i][j]=getMax(m[i-1][j],m[i][j-1],m[i-1][j-1]);
            }
        }
    }
    return m[la][lb];
}

int main(){
    while(cin>>a>>b){
        cout<<getLCS()<<endl;
    }
    return 0;
}

  








相关文章:

  • 2021-08-21
  • 2021-11-25
  • 2022-12-23
  • 2022-01-08
  • 2021-11-17
  • 2022-03-07
  • 2021-07-30
  • 2022-01-14
猜你喜欢
  • 2021-07-28
  • 2022-01-30
  • 2021-06-06
  • 2021-12-15
  • 2021-08-21
  • 2021-09-15
  • 2021-07-30
相关资源
相似解决方案