fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. String longestPalindrome(String str) {
  11.  
  12. if (str.length() <= 1)
  13. return str;
  14.  
  15. String LPS = "";
  16.  
  17. for (int i = 1; i < str.length(); i++) {
  18.  
  19. // Consider odd length
  20. int low = i;
  21. int high = i;
  22. while(str.charAt(low) == str.charAt(high)) {
  23. low--;
  24. high++;
  25.  
  26. if (low == -1 || high == str.length())
  27. break;
  28. }
  29.  
  30. String palindrome = str.substring(low+1, high);
  31. if (palindrome.length() > LPS.length()) {
  32. LPS = palindrome;
  33. }
  34.  
  35. // Consider even length
  36. low = i-1;
  37. high = i;
  38. while(str.charAt(low) == str.charAt(high)) {
  39. low--;
  40. high++;
  41.  
  42. if (low == -1 || high == str.length())
  43. break;
  44. }
  45.  
  46. palindrome = str.substring(low+1, high);
  47. if (palindrome.length() > LPS.length()) {
  48. LPS = palindrome;
  49. }
  50. }
  51.  
  52. return LPS;
  53. }
  54.  
  55. public static void main (String[] args) throws java.lang.Exception
  56. {
  57. // your code goes here
  58. Ideone x = new Ideone();
  59. System.out.println(x.longestPalindrome("aaebabad"));
  60. System.out.println(x.longestPalindrome("cbeereed"));
  61. }
  62. }
Success #stdin #stdout 0.06s 32432KB
stdin
Standard input is empty
stdout
bab
eeree