|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to compute the longest common subsequence using optimized space |
| 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 two 1D arrays for the current and next rows in the DP table |
| 9 | + // This reduces the space complexity to O(m) instead of O(n*m) |
| 10 | + vector<int> curr(m + 1, 0); // Current row being processed |
| 11 | + vector<int> next(m + 1, 0); // Next row (from the previous iteration) |
| 12 | + |
| 13 | + // Iterate over the strings in reverse order |
| 14 | + for (int i = n - 1; i >= 0; i--) { |
| 15 | + for (int j = m - 1; j >= 0; j--) { |
| 16 | + int ans = 0; // Variable to store the result for the current state |
| 17 | + |
| 18 | + // Case 1: Characters match, include them in the LCS |
| 19 | + if (text1[i] == text2[j]) |
| 20 | + ans = 1 + next[j + 1]; |
| 21 | + else |
| 22 | + // Case 2: Characters don't match, take the maximum: |
| 23 | + // a) Skip the current character of text1 |
| 24 | + // b) Skip the current character of text2 |
| 25 | + ans = max(next[j], curr[j + 1]); |
| 26 | + |
| 27 | + // Store the result in the current row |
| 28 | + curr[j] = ans; |
| 29 | + } |
| 30 | + |
| 31 | + // Update the next row to the current row for the next iteration |
| 32 | + next = curr; |
| 33 | + } |
| 34 | + |
| 35 | + // The final answer (LCS of the entire strings) is stored in curr[0] |
| 36 | + return curr[0]; |
| 37 | + } |
| 38 | + |
| 39 | + // Main function to compute the longest common subsequence |
| 40 | + int longestCommonSubsequence(string text1, string text2) { |
| 41 | + // Call the helper function and return the result |
| 42 | + return solve(text1, text2); |
| 43 | + } |
| 44 | +}; |
0 commit comments