|
1 |
| - |
2 |
| - |
3 | 1 | char* longestPalindrome(char* s) {
|
4 | 2 | int n = strlen(s);
|
5 |
| - if (n == 0) { |
6 |
| - char* result = malloc(1); |
7 |
| - result[0] = '\0'; |
8 |
| - return result; |
9 |
| - } |
10 |
| - |
11 |
| - bool dp[n][n]; |
12 |
| - memset(dp, 0, sizeof(dp)); |
13 |
| - |
14 |
| - int start = 0, max_len = 1; |
15 |
| - |
16 |
| - for (int i = 0; i < n; i++) { |
17 |
| - dp[i][i] = true; |
18 |
| - } |
19 |
| - |
20 |
| - for (int i = 0; i < n - 1; i++) { |
21 |
| - if (s[i] == s[i + 1]) { |
22 |
| - dp[i][i + 1] = true; |
23 |
| - start = i; |
24 |
| - max_len = 2; |
| 3 | + bool** f = (bool**) malloc(n * sizeof(bool*)); |
| 4 | + for (int i = 0; i < n; ++i) { |
| 5 | + f[i] = (bool*) malloc(n * sizeof(bool)); |
| 6 | + for (int j = 0; j < n; ++j) { |
| 7 | + f[i][j] = true; |
25 | 8 | }
|
26 | 9 | }
|
27 |
| - |
28 |
| - // Check for lengths > 2 |
29 |
| - for (int len = 3; len <= n; len++) { |
30 |
| - for (int i = 0; i < n - len + 1; i++) { |
31 |
| - int j = i + len - 1; |
32 |
| - if (s[i] == s[j] && dp[i + 1][j - 1]) { |
33 |
| - dp[i][j] = true; |
34 |
| - if (len > max_len) { |
35 |
| - start = i; |
36 |
| - max_len = len; |
| 10 | + int k = 0, mx = 1; |
| 11 | + for (int i = n - 2; ~i; --i) { |
| 12 | + for (int j = i + 1; j < n; ++j) { |
| 13 | + f[i][j] = false; |
| 14 | + if (s[i] == s[j]) { |
| 15 | + f[i][j] = f[i + 1][j - 1]; |
| 16 | + if (f[i][j] && mx < j - i + 1) { |
| 17 | + mx = j - i + 1; |
| 18 | + k = i; |
37 | 19 | }
|
38 | 20 | }
|
39 | 21 | }
|
40 | 22 | }
|
41 |
| - char* result = malloc(max_len + 1); |
42 |
| - strncpy(result, s + start, max_len); |
43 |
| - result[max_len] = '\0'; |
44 |
| - return result; |
| 23 | + char* res = (char*) malloc((mx + 1) * sizeof(char)); |
| 24 | + strncpy(res, s + k, mx); |
| 25 | + res[mx] = '\0'; |
| 26 | + for (int i = 0; i < n; ++i) { |
| 27 | + free(f[i]); |
| 28 | + } |
| 29 | + free(f); |
| 30 | + return res; |
45 | 31 | }
|
0 commit comments