Problem:
Given a string of lower case letters in the range ascii[a-z], identify the index of character to be removed to change the string into a palindrome. If the string cannot be converted to palindrome or is already a palindrome just return -1 else return index of the character to be removed.
My Solution:
public static int palindromeIndex(String s) {
if(p(s)){
return -1;
}
StringBuilder sb = new StringBuilder(s);
for(int i=0; i<s.length(); i++){
sb.deleteCharAt(i);
if(p(sb.toString())){
return i;
}
sb.insert(i,s.charAt(i));
}
return -1;
}
private static boolean p(String s){
for(int i=0; i<s.length()/2; i++){
if(s.charAt(i) != s.charAt(s.length() - i - 1)){
return false;
}
}
return true;
}
It is failing for one or all below test cases (unable to determine for which one) according to hackerrank:
- quyjjdcgsvvsgcdjjyq
- hgygsvlfwcwnswtuhmyaljkqlqjjqlqkjlaymhutwsnwcflvsgygh
- fgnfnidynhxebxxxfmxixhsruldhsaobhlcggchboashdlurshxixmfxxxbexhnydinfngf
- bsyhvwfuesumsehmytqioswvpcbxyolapfywdxeacyuruybhbwxjmrrmjxwbhbyuruycaexdwyfpaloyxbcpwsoiqtymhesmuseufwvhysb
- fvyqxqxynewuebtcuqdwyetyqqisappmunmnldmkttkmdlnmnumppasiqyteywdquctbeuwenyxqxqyvf
- mmbiefhflbeckaecprwfgmqlydfroxrblulpasumubqhhbvlqpixvvxipqlvbhqbumusaplulbrxorfdylqmgfwrpceakceblfhfeibmm
- tpqknkmbgasitnwqrqasvolmevkasccsakvemlosaqrqwntisagbmknkqpt
- lhrxvssvxrhl
- prcoitfiptvcxrvoalqmfpnqyhrubxspplrftomfehbbhefmotfrlppsxburhyqnpfmqlaorxcvtpiftiocrp
- kjowoemiduaaxasnqghxbxkiccikxbxhgqnsaxaaudimeowojk
My Output:
- 1
- 8
- 33
- 23
- 24
- 43
- 20
- -1
- 14
- -1
I debugged to code locally, and according to my understanding, this test case is working fine. Please help me out understating, what is wrong with the code.
Note: I can do it with other alternative ways (more simpler ways), solutions are available online, but i am trying to understand, what is wrong with my piece of java code. Thanks.