Skip to content

Commit 6d11de0

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 2e5a746 commit 6d11de0

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the longest palindromic subsequence using space optimization
4+
// Parameters:
5+
// - str: the original string
6+
// - revStr: the reversed string
7+
int solve(string str, string revStr) {
8+
int n = str.length(); // Length of the original string
9+
int m = revStr.length(); // Length of the reversed string
10+
11+
// Two 1D arrays to represent the current and next rows of the dp table
12+
// `curr[j]`: Represents dp[i][j] for the current row
13+
// `next[j]`: Represents dp[i+1][j] for the next row
14+
vector<int> curr(m + 1, 0); // Initialize the current row with 0
15+
vector<int> next(m + 1, 0); // Initialize the next row with 0
16+
17+
// Traverse the dp table from bottom-right to top-left
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 result for dp[i][j]
21+
22+
// If the characters match, add 1 to the result from the diagonal (next[j+1])
23+
if (str[i] == revStr[j]) {
24+
ans = 1 + next[j + 1]; // Move diagonally (i+1, j+1)
25+
} else {
26+
// If the characters do not match, take the maximum of:
27+
// - The value from the row below (next[j]) representing dp[i+1][j]
28+
// - The value from the column to the right in the current row (curr[j+1])
29+
ans = max(next[j], curr[j + 1]);
30+
}
31+
32+
// Store the computed result in the current row
33+
curr[j] = ans;
34+
}
35+
36+
// Update the `next` row to become the current row for the next iteration
37+
next = curr;
38+
}
39+
40+
// The result is stored in `curr[0]`, which represents dp[0][0]
41+
return curr[0];
42+
}
43+
44+
// Main function to calculate the longest palindromic subsequence
45+
int longestPalindromeSubseq(string str) {
46+
// Create a reversed copy of the original string
47+
string revStr = str;
48+
reverse(revStr.begin(), revStr.end());
49+
50+
// Call the helper function to calculate the result
51+
return solve(str, revStr);
52+
}
53+
};

0 commit comments

Comments
 (0)