Coincidence

来源:互联网 发布:齐白石真迹价格 知乎 编辑:程序博客网 时间:2024/05/17 07:36
题目描述:

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


#include <iostream>#include <string> using namespace std; int dp[101][101]; int max(int a,int b){    return a>b?a:b;} int main(){    string str1,str2;    int i,j;    while(cin>>str1>>str2)    {        int len1 = str1.length();        int len2 = str2.length();        for(i = 0;i <= len1;i++)        {            dp[i][0] = 0;        }        for(j = 0;j <= len2;j++)        {            dp[0][j] = 0;        }        for(i = 1;i <= len1;i++)        {            for(j = 1;j <= len2;j++)            {                if(str1[i-1] != str2[j-1])                {                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);                }                else                {                    dp[i][j] = dp[i-1][j-1] + 1;                }            }        }        cout<<dp[len1][len2]<<endl;    }    return 0;} /**************************************************************    Problem: 1042    User: 19930124wu    Language: C++    Result: Accepted    Time:0 ms    Memory:1560 kb****************************************************************/

最长公共子序列:

最长公共子序列问题的递推条件

dp[i][0] = 0;

dp[0][j] = 0;

dp[i][j] = dp[i-1][j-1](S1[i]==S2[j])

dp[i][j] = max{dp[i-1][j] dp[i][j-1] }(S1[i]!=S2[j])

用dp[i][j]表示S1前i个字符组成的前缀子串与S2前j个字符组成的前缀子串的最长公共子串长度

0 0
原创粉丝点击