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. private static boolean isPalindrome(char[] data, int left, int right) {
  11. while (left <= right) {
  12. if (data[left] != data[right]) {
  13. return false;
  14. }
  15. left++;
  16. right--;
  17. }
  18. return true;
  19. }
  20.  
  21. public static int whichCharForPalindrome(final String input) {
  22. final char[] letters = input.toCharArray();
  23. int left = 0;
  24. int right = letters.length - 1;
  25.  
  26. // look for the mismatch:
  27. while (left < right && letters[left] == letters[right]) {
  28. left++;
  29. right--;
  30. }
  31.  
  32. // OK, if there's no broken letter in this palindrome....
  33. if (left >= right) {
  34. // the data is a palindrome, so removing (one of) the middle chars is fine.
  35. // so remove the middle one.
  36. return left;
  37. }
  38.  
  39. // removing the left makes a palindrome.
  40. if (isPalindrome(letters, left + 1, right)) {
  41. return left;
  42. }
  43.  
  44. // removing the right makes a palindrome.
  45. if (isPalindrome(letters, left, right - 1)) {
  46. return right;
  47. }
  48. throw new IllegalStateException("We were supposed to be able to remove a char "
  49. + "to make a palindrome, but could not");
  50. }
  51.  
  52. public static void main(String[] args) {
  53. String[] candidates = {"abcdedcba", "ablxe was I ere I saw elba"};
  54. for (String input : candidates) {
  55. int pos = whichCharForPalindrome(input);
  56. System.out.printf("Remove '%c' (at %d) from '%s' to make palindrome: %s\n",
  57. input.charAt(pos), pos, input, input.substring(0, pos) + input.substring(pos + 1));
  58. }
  59. }
  60. }
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
Remove 'e' (at 4) from 'abcdedcba' to make palindrome: abcddcba
Remove 'x' (at 3) from 'ablxe was I ere I saw elba' to make palindrome: able was I ere I saw elba