The Longest Common Subsequence (LCS) problem is a classic problem in computer science. It aims to find the longest subsequence present in two sequences (strings in this case) such that the subsequence appears in both strings in the same order.

Program Structure

  • Input: Two strings for which we want to find the LCS.
  • Output: The length of the LCS and the LCS itself.
  • Dynamic Programming: The program uses a 2D array to store the lengths of longest common subsequences for different substrings.

C++ Code


#include <iostream>
#include <string>
#include <vector>

using namespace std;

// Function to find the length of LCS and the LCS itself
pair<int, string> longestCommonSubsequence(const string &s1, const string &s2) {
    int m = s1.length();
    int n = s2.length();
    
    // Create a 2D vector to store lengths of LCS
    vector<vector<int>> lcs(m + 1, vector<int>(n + 1, 0));

    // Build the lcs array in bottom-up fashion
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s1[i - 1] == s2[j - 1]) {
                lcs[i][j] = lcs[i - 1][j - 1] + 1;
            } else {
                lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]);
            }
        }
    }

    // The length of the LCS is in lcs[m][n]
    int length = lcs[m][n];
    
    // To construct the LCS string
    string lcsString;
    int i = m, j = n;
    while (i > 0 && j > 0) {
        if (s1[i - 1] == s2[j - 1]) {
            lcsString.push_back(s1[i - 1]);
            i--;
            j--;
        } else if (lcs[i - 1][j] > lcs[i][j - 1]) {
            i--;
        } else {
            j--;
        }
    }
    
    // The LCS string is constructed in reverse order
    reverse(lcsString.begin(), lcsString.end());

    return make_pair(length, lcsString);
}

int main() {
    string str1, str2;

    // Input strings
    cout << "Enter first string: ";
    cin >> str1;
    cout << "Enter second string: ";
    cin >> str2;

    // Find LCS
    pair<int, string> result = longestCommonSubsequence(str1, str2);
    
    // Output the result
    cout << "Length of LCS: " << result.first << endl;
    cout << "Longest Common Subsequence: " << result.second << endl;

    return 0;
}

Explanation of the Code

The code consists of the following main components:

  • Input Handling: The program prompts the user to enter two strings.
  • LCS Calculation: The longestCommonSubsequence function uses dynamic programming to calculate the LCS. It fills a 2D vector lcs where lcs[i][j] holds the length of LCS of substrings s1[0..i-1] and s2[0..j-1].
  • LCS Construction: After computing the lengths, the function constructs the LCS string by backtracking through the lcs vector.
  • Output: The program displays the length of the LCS and the LCS itself.

Conclusion

This program efficiently finds the longest common subsequence using dynamic programming, making it suitable for handling larger strings compared to a naive recursive approach.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)