Count common subsequence in two strings

Write a program to count the common subsequence in two strings.

Example:

Input:  str1="abcd", str2="abd"
Output: 7

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int commonSubsequence(string str1string str2)
{
    int n = str1.size(), m = str2.size();

    int dp[n + 1][m + 1];

    memset(dp0sizeof(dp));
    for (int i = 1i <= ni++)
    {
        for (int j = 1j <= mj++)
        {
            if (str1[i - 1] == str2[j - 1])
            {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + 1;
            }
            else
            {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - 
dp[i - 1][j - 1];
            }
        }
    }
    return dp[n][m];
}

int main()
{
    string str1 = "abcd";
    string str2 = "abd";

    cout << commonSubsequence(str1str2);

    return 0;
}


No comments:

Post a Comment