Skip to content

Commit 3a848c3

Browse files
committed
Time: 410 ms (35.25%), Space: 11.1 MB (60.87%) - LeetHub
1 parent 4468e7a commit 3a848c3

File tree

1 file changed

+38
-28
lines changed

1 file changed

+38
-28
lines changed
Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,50 @@
11
class Solution {
22
public:
3-
pair<int,int> checkPal(int i, int j, int n, string& str) {
4-
while(i >= 0 and j < n and str[i] == str[j]) {
5-
i--,j++;
3+
string longestPalindrome(string str) {
4+
int n = str.size();
5+
int dp[n][n];// dp[i][j] = 1 if str[i][j] is a palindrome
6+
// = 0, otherwise
7+
8+
for(int i = 0; i < n; i++) {
9+
for(int j = 0; j < n; j++) {
10+
dp[i][j] = 0;
611
}
7-
i++,j--;
12+
}
813

9-
return {i,j};
10-
// sz = max(sz, j - i + 1);
11-
}
14+
// 1 len
15+
for(int i = 0; i < n; i++) {
16+
dp[i][i] = 1;
17+
}
1218

13-
string longestPalindrome(string str) {
14-
int n = str.size();
15-
int centers = 2*n - 1;
16-
// * * * * * * *
17-
// 0 1 2 3
18-
// c
19-
int sz = 0;
20-
int l = -1, r = -1;
21-
for(int c = 0; c < n; c++) {
22-
// int i = c - 1, j = c + 1;
23-
pair<int,int> p1 = checkPal(c-1,c+1,n, str);
24-
pair<int, int> p2 = checkPal(c,c+1,n, str);
25-
if((p1.second - p1.first + 1) >= sz) {
26-
sz = (p1.second - p1.first + 1);
27-
l = p1.first;
28-
r = p1.second;
19+
// 2 len
20+
for(int i = 0; i < n-1; i++) {
21+
dp[i][i+1] = (str[i] == str[i+1]) ? 1 : 0;
22+
}
23+
24+
// >= 3 len
25+
for(int l = 3; l <= n; l++) {
26+
for(int i = 0; i < n - l + 1; i++) {
27+
int j = i + l - 1;
28+
// i-j
29+
if(str[i] == str[j] && dp[i+1][j-1]){
30+
dp[i][j] = 1;
31+
} else
32+
dp[i][j] = 0;
2933
}
34+
}
3035

31-
if((p2.second - p2.first + 1) >= sz) {
32-
sz = (p2.second - p2.first + 1);
33-
l = p2.first;
34-
r = p2.second;
36+
// find lps
37+
int sz = 0;
38+
int start = 0;
39+
for(int i = 0; i < n; i++) {
40+
for(int j = 0; j < n; j++) {
41+
if(dp[i][j] and (j-i+1) > sz) {
42+
sz = j - i + 1;
43+
start = i;
44+
}
3545
}
3646
}
3747

38-
return str.substr(l, sz);
48+
return str.substr(start, sz);
3949
}
4050
};

0 commit comments

Comments
 (0)