Skip to content

Commit 48677b6

Browse files
committed
Longest Palindromic Substring DP way, but Memory Limit Exceeded error
1 parent f3428f9 commit 48677b6

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/longestPalindromicSubstring/longestPalindromicSubstring.cpp

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
#include <iostream>
1414
#include <string>
15+
#include <vector>
1516
using namespace std;
1617

1718
string findPalindrome(string s, int left, int right)
@@ -27,7 +28,7 @@ string findPalindrome(string s, int left, int right)
2728
}
2829

2930

30-
string longestPalindrome(string s) {
31+
string longestPalindrome_recursive_way(string s) {
3132
int n = s.size();
3233
if (n<=1) return s;
3334

@@ -48,6 +49,40 @@ string longestPalindrome(string s) {
4849
return longest;
4950
}
5051

52+
//Memory Limit Exceeded
53+
string longestPalindrome_dp_way(string s) {
54+
55+
string longest;
56+
57+
int n = s.size();
58+
if (n<=1) return s;
59+
60+
//Construct a matrix, and consdier matrix[i][j] as s[i] -> s[j] is Palindrome or not.
61+
vector< vector<int> > matrix (n, vector<int>(n));
62+
63+
// Dynamic Programming
64+
// 1) if i == j, then matrix[i][j] = true;
65+
// 2) if i != j, then matrix[i][j] = (s[i]==s[j] && matrix[i+1][j-1])
66+
for (int i=n-1; i>=0; i--){
67+
for (int j=i; j<n; j++){
68+
// The following if statement can be broken to
69+
// 1) i==j, matrix[i][j] = true
70+
// 2) the length from i to j is 2 or 3, then, check s[i] == s[j]
71+
// 3) the length from i to j > 3, then, check s[i]==s[j] && matrix[i+1][j-1]
72+
if ( i==j || (s[i]==s[j] && (j-i<2 || matrix[i+1][j-1]) ) ) {
73+
matrix[i][j] = true;
74+
if (longest.size() < j-i+1){
75+
longest = s.substr(i, j-i+1);
76+
}
77+
}
78+
}
79+
}
80+
81+
return longest;
82+
}
83+
string longestPalindrome(string s) {
84+
return longestPalindrome_dp_way(s);
85+
}
5186

5287
int main(int argc, char**argv)
5388
{

0 commit comments

Comments
 (0)