[Jobdu] 题目1042:Coincidence

题目描述:

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;
}

  








posted @ 2012-07-30 22:36  Eason Liu  阅读(276)  评论(0编辑  收藏  举报