fork(1) download
  1. import java.util.Scanner;
  2.  
  3. // By nikoo28
  4. class PalindromeIndex {
  5.  
  6. static boolean isPalindrome(String str) {
  7.  
  8. int n = str.length();
  9. for (int i = 0; i < n / 2; i++)
  10. if (str.charAt(i) != str.charAt(n - i - 1)) return false;
  11. return true;
  12. }
  13.  
  14. static int palindromeIndex(String s) {
  15.  
  16. int start = 0;
  17. int end = s.length() - 1;
  18.  
  19. if (isPalindrome(s))
  20. return -1;
  21.  
  22. while (true) {
  23.  
  24. if (start > end)
  25. break;
  26.  
  27. // Code obtained from studyalgorithms.com
  28. // Feel free to copy but please acknowledge wherever possible.
  29. if (s.charAt(start) == s.charAt(end)) {
  30. start++;
  31. end--;
  32. continue;
  33. }
  34.  
  35. // Create string after removing start
  36. if (isPalindrome(s.substring(0, start) + s.substring(start + 1))) {
  37. return start;
  38. } else if (isPalindrome(s.substring(0, end) + s.substring(end + 1))) {
  39. return end;
  40. } else
  41. return -1;
  42. }
  43.  
  44. return -1;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Scanner in = new Scanner(System.in);
  49. int q = in.nextInt();
  50. for (int a0 = 0; a0 < q; a0++) {
  51. String s = in.next();
  52. int result = palindromeIndex(s);
  53. System.out.println(result);
  54. }
  55. }
  56. }
  57.  
Success #stdin #stdout 0.06s 4386816KB
stdin
1
abckdeedcba
stdout
3