1. class Solution {
  2. public String longestPalindrome(String s) {
  3. String s2 = new StringBuilder(s).reverse().toString();
  4.  
  5. int n = s.length();
  6. int m = s2.length();
  7.  
  8. // create a matrix
  9. int[][] t = new int[n+1][m+1];
  10.  
  11. // intialise the matrix with base condition
  12. for(int i=0; i<n+1; i++)
  13. {
  14. for(int j=0; j<m+1; j++)
  15. {
  16. if(i == 0 || j == 0)
  17. t[i][j] = 0;
  18. }
  19. }
  20.  
  21. // find LCS
  22. int maxLength = 0;
  23. int endIndex = 0;
  24. for(int i=1; i<n+1; i++)
  25. {
  26. for(int j=1; j<m+1; j++)
  27. {
  28. if(s.charAt(i-1) == s2.charAt(j-1))
  29. {
  30. t[i][j] = 1 + t[i-1][j-1];
  31. int currentLength = t[i][j];
  32.  
  33. // start index in original string
  34. // If a substring of length len ends at i-1 in s, its start index in s is:
  35. int startIndex = i - currentLength;
  36. // In the reversed string, the corresponding start should be: (n-j)
  37. int mirroredIndex = n - j;
  38.  
  39. // check alignment
  40. if(startIndex == mirroredIndex)
  41. {
  42. if(currentLength > maxLength)
  43. {
  44. maxLength = currentLength;
  45. endIndex = i-1;
  46. }
  47. }
  48. }
  49. }
  50. }
  51. return s.substring(endIndex - maxLength + 1, endIndex + 1);
  52. }
  53. }