|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the longest palindromic subsequence using dynamic programming |
| 4 | + // Parameters: |
| 5 | + // - str: the original string |
| 6 | + // - revStr: the reversed string |
| 7 | + // - i: current index in the original string |
| 8 | + // - j: current index in the reversed string |
| 9 | + int solve(string str, string revStr, int i, int j) { |
| 10 | + int n = str.length(); // Length of the original string |
| 11 | + int m = revStr.length(); // Length of the reversed string |
| 12 | + |
| 13 | + // 2D dp table to store the length of the longest palindromic subsequence |
| 14 | + // dp[i][j] represents the longest common subsequence between str[i..n-1] and revStr[j..m-1] |
| 15 | + vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); // Initialize with 0 |
| 16 | + |
| 17 | + // Bottom-up dynamic programming approach: start from the end of both strings |
| 18 | + for (int i = n - 1; i >= 0; i--) { |
| 19 | + for (int j = m - 1; j >= 0; j--) { |
| 20 | + int ans = 0; // Variable to store the current result |
| 21 | + |
| 22 | + // If characters match, add 1 to the result and check the next characters in both strings |
| 23 | + if (str[i] == revStr[j]) { |
| 24 | + ans = 1 + dp[i + 1][j + 1]; // Move diagonally (i+1, j+1) |
| 25 | + } |
| 26 | + // If characters do not match, take the maximum of two possible options |
| 27 | + // - Move forward in the original string (i+1, j) |
| 28 | + // - Move forward in the reversed string (i, j+1) |
| 29 | + else { |
| 30 | + ans = max(dp[i + 1][j], dp[i][j + 1]); |
| 31 | + } |
| 32 | + |
| 33 | + // Store the computed result in the dp table |
| 34 | + dp[i][j] = ans; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Return the result stored at dp[0][0], which represents the length of the longest palindromic subsequence |
| 39 | + return dp[0][0]; |
| 40 | + } |
| 41 | + |
| 42 | + // Main function to calculate the longest palindromic subsequence |
| 43 | + int longestPalindromeSubseq(string str) { |
| 44 | + // Create the reversed version of the input string |
| 45 | + string revStr = str; |
| 46 | + reverse(revStr.begin(), revStr.end()); // Reverse the string |
| 47 | + |
| 48 | + // Call the helper function to calculate the longest palindromic subsequence |
| 49 | + return solve(str, revStr, 0, 0); |
| 50 | + } |
| 51 | +}; |
0 commit comments