You are given a string of lowercase letters. Your task is to figure out the index of the character whose removal will result in a palindrome. There will always be a valid solution.
Here is my quick solution:
public class Main {
private static final String AAA = "aaa";
public static void main(String[] args) {
System.out.println(palindromeIndex(AAA));
}
/**
* Returns whether a word is palindromic or not
* @param word
* @return true if the word is palindromic, false otherwise
*/
public static boolean isPalindrome(String word) {
return word.equals(new StringBuffer().append(word).reverse().toString());
}
public static int palindromeIndex(String word) {
if(isPalindrome(word)) {
return -1;
}
StringBuffer sb = new StringBuffer();
for(int i = 0; i < word.length(); i++) {
sb.append(word);
sb.deleteCharAt(i);
if(isPalindrome(sb.toString())) {
return i;
}
sb.delete(0, word.length());
}
/**the question said that there will always be a valid answer
* so this shouldn't be necessary
*/
return - 1;
}
}
Additionally, out of a little dissatisfaction, I came up with an alternative method of figuring out whether a word is a palindrome:
public static boolean isPalindromeAlt(String word) {
char[] chars = word.toCharArray();
int wordEnd = word.length() - 1;
for(int i = 0; i < chars.length; i++) {
if(chars[i] != chars[wordEnd]) {
return false;
}
wordEnd--;
}
return true;
}
But my question is, after actually thinking about it, is the way I have handled the palindrome index part efficient? I don't really like the fact that I am clearing a the stringbuffer after each iteration and using one, I thought that it might be more efficient to use an array or something, could someone please comment on whether my solution is efficient and whether there could be a more efficient way.
I could probably write a more efficient one in Python, I like how Strings are handled as arrays in it.