|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive helper function to solve the problem |
| 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 | + // Base case: if either index goes out of bounds, return 0 |
| 11 | + if (i >= str.length() || j >= revStr.length()) |
| 12 | + return 0; |
| 13 | + |
| 14 | + // Initialize the answer variable |
| 15 | + int ans = 0; |
| 16 | + |
| 17 | + // If the characters match, add 1 to the result and move to the next indices |
| 18 | + if (str[i] == revStr[j]) |
| 19 | + return 1 + solve(str, revStr, i + 1, j + 1); |
| 20 | + else { |
| 21 | + // If the characters do not match, find the maximum result by: |
| 22 | + // 1. Skipping the current character in the original string |
| 23 | + // 2. Skipping the current character in the reversed string |
| 24 | + ans = max(solve(str, revStr, i + 1, j), solve(str, revStr, i, j + 1)); |
| 25 | + } |
| 26 | + |
| 27 | + // Return the computed answer |
| 28 | + return ans; |
| 29 | + } |
| 30 | + |
| 31 | + // Function to calculate the longest palindromic subsequence |
| 32 | + int longestPalindromeSubseq(string str) { |
| 33 | + // Create a reversed version of the input string |
| 34 | + string revStr = str; |
| 35 | + reverse(revStr.begin(), revStr.end()); |
| 36 | + |
| 37 | + // Start solving from the first indices of both strings |
| 38 | + return solve(str, revStr, 0, 0); |
| 39 | + } |
| 40 | +}; |
0 commit comments