Q2. Print length longest subsequence from two given strings
Utilisateur anonyme
Approach -> Dynamic Programming Table: Create a 2D array dp where dp[i][j] represents the length of the longest common subsequence of the first i characters of string s1 and the first j characters of string s2. Initialization: Initialize the first row and the first column of the dp table to 0. This is because the LCS of any string with an empty string is 0. Filling the DP Table: Iterate through each character of both strings. If the characters match (s1[i-1] == s2[j-1]), then dp[i][j] = dp[i-1][j-1] + 1. If the characters do not match, then dp[i][j] = max(dp[i-1][j], dp[i][j-1]) Result: The value at dp[m][n] (where m and n are the lengths of s1 and s2 respectively) will be the length of the longest common subsequence. Time Complexity: The time complexity is O(m * n), where m is the length of string s1 and n is the length of string s2. This is because we need to fill an m x n table. Space Complexity: The space complexity is O(m * n) for the dp table. However, this can be optimized to O(min(m, n)) by using a rolling array technique, but for simplicity, we'll use the full dp table here.