@@ -275,6 +275,42 @@ public class Solution {
275275}
276276```
277277
278+ #### C
279+
280+ ``` c
281+ char * longestPalindrome (char* s) {
282+ int n = strlen(s);
283+ bool** f = (bool** ) malloc(n * sizeof(bool* ));
284+ for (int i = 0; i < n; ++i) {
285+ f[ i] = (bool* ) malloc(n * sizeof(bool));
286+ for (int j = 0; j < n; ++j) {
287+ f[ i] [ j ] = true;
288+ }
289+ }
290+ int k = 0, mx = 1;
291+ for (int i = n - 2; ~ i; --i) {
292+ for (int j = i + 1; j < n; ++j) {
293+ f[ i] [ j ] = false;
294+ if (s[ i] == s[ j] ) {
295+ f[ i] [ j ] = f[ i + 1] [ j - 1 ] ;
296+ if (f[ i] [ j ] && mx < j - i + 1) {
297+ mx = j - i + 1;
298+ k = i;
299+ }
300+ }
301+ }
302+ }
303+ char* res = (char* ) malloc((mx + 1) * sizeof(char));
304+ strncpy(res, s + k, mx);
305+ res[ mx] = '\0';
306+ for (int i = 0; i < n; ++i) {
307+ free(f[ i] );
308+ }
309+ free(f);
310+ return res;
311+ }
312+ ```
313+
278314#### Nim
279315
280316```nim
@@ -525,55 +561,6 @@ class Solution {
525561}
526562```
527563
528- #### C
529-
530- ``` c
531- char *longestPalindrome (char * s) {
532- int n = strlen(s);
533- if (n == 0) {
534- char * result = malloc(1);
535- result[ 0] = '\0';
536- return result;
537- }
538-
539- bool dp[ n] [ n ] ;
540- memset(dp, 0, sizeof(dp));
541-
542- int start = 0, max_len = 1;
543-
544- for (int i = 0; i < n; i++) {
545- dp[ i] [ i ] = true;
546- }
547-
548- for (int i = 0; i < n - 1; i++) {
549- if (s[ i] == s[ i + 1] ) {
550- dp[ i] [ i + 1 ] = true;
551- start = i;
552- max_len = 2;
553- }
554- }
555-
556- // Check for lengths > 2
557- for (int len = 3; len <= n; len++) {
558- for (int i = 0; i < n - len + 1; i++) {
559- int j = i + len - 1;
560- if (s[ i] == s[ j] && dp[ i + 1] [ j - 1 ] ) {
561- dp[ i] [ j ] = true;
562- if (len > max_len) {
563- start = i;
564- max_len = len;
565- }
566- }
567- }
568- }
569- char * result = malloc(max_len + 1);
570- strncpy(result, s + start, max_len);
571- result[ max_len] = '\0';
572- return result;
573- }
574-
575- ```
576-
577564<!-- tabs: end -->
578565
579566<!-- solution: end -->
0 commit comments