|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to compute the longest common subsequence using bottom-up dynamic programming |
| 4 | + int solve(string &text1, string &text2) { |
| 5 | + int n = text1.length(); // Length of the first string |
| 6 | + int m = text2.length(); // Length of the second string |
| 7 | + |
| 8 | + // Create a 2D DP table initialized with 0 |
| 9 | + // dp[i][j] represents the length of the LCS of text1[i..n-1] and text2[j..m-1] |
| 10 | + vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); |
| 11 | + |
| 12 | + // Iterate over the strings in reverse order to fill the DP table |
| 13 | + for (int i = n - 1; i >= 0; i--) { |
| 14 | + for (int j = m - 1; j >= 0; j--) { |
| 15 | + int ans = 0; // Variable to store the result for the current state |
| 16 | + |
| 17 | + // Case 1: Characters match, include them in the LCS |
| 18 | + if (text1[i] == text2[j]) |
| 19 | + ans = 1 + dp[i + 1][j + 1]; |
| 20 | + else |
| 21 | + // Case 2: Characters don't match, take the maximum: |
| 22 | + // a) Skip the current character of text1 |
| 23 | + // b) Skip the current character of text2 |
| 24 | + ans = max(dp[i + 1][j], dp[i][j + 1]); |
| 25 | + |
| 26 | + // Store the result in the DP table |
| 27 | + dp[i][j] = ans; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + // The final answer (LCS of the entire strings) is stored in dp[0][0] |
| 32 | + return dp[0][0]; |
| 33 | + } |
| 34 | + |
| 35 | + // Main function to compute the longest common subsequence |
| 36 | + int longestCommonSubsequence(string text1, string text2) { |
| 37 | + // Call the helper function and return the result |
| 38 | + return solve(text1, text2); |
| 39 | + } |
| 40 | +}; |
0 commit comments