fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5.  
  6. char* longestPalindrome(char* s) {
  7. int n = strlen(s) ;
  8. if(n <= 1)
  9. return s ;
  10. int i, j, l ;
  11. bool table[1000][1000] ;
  12. for(i = 0 ; i < n ; i++)
  13. table[i][i] = true ;
  14. int start = 0, maxLength = 1 ;
  15.  
  16. for(l = 2 ; l <= n ; l++) {
  17. for(i = 0 ; i < n-l+1 ; i++) {
  18. j = i+l-1 ;
  19. if(l == 2) {
  20. if(s[i] == s[j]) {
  21. table[i][j] = true ;
  22. start = i ;
  23. maxLength = 2 ;
  24. }
  25. }
  26. else {
  27. if(table[i+1][j-1] && (s[i] == s[j]) ) {
  28. table[i][j] = true ;
  29. if(l > maxLength) {
  30. start = i ;
  31. maxLength = l ;
  32. }
  33. }
  34. }
  35. }
  36. }
  37. char *pal = (char *)malloc((maxLength+1) * sizeof(char) ) ;
  38. for(i = start, j = 0 ; i <= start + maxLength - 1 ; i++, j++)
  39. pal[j] = s[i] ;
  40. pal[j] = '\0' ;
  41. return pal ;
  42. }
  43.  
  44. int main() {
  45. char str[] = "aaabaaaa" ;
  46. char *s = longestPalindrome(str) ;
  47. printf("%s",s) ;
  48. return 0 ;
  49. }
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
aaabaaa