We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
private static int findIndexOfMismatch(String s) {
for(int i=0 ; i
public static int palindromeIndex(String s) {
int mismatchIndex = findIndexOfMismatch(s);
if(mismatchIndex==-1) {
// is already a palindrome
return -1;
}
// option 1 - remove mismatching char at the left and check
String maybePalindrome = s.substring(mismatchIndex+1, s.length()-mismatchIndex);
if(findIndexOfMismatch(maybePalindrome)==-1) {
return mismatchIndex;
}
// option 2 - remove mismatching char at the right and check
maybePalindrome = s.substring(mismatchIndex, s.length()-mismatchIndex-1);
if(findIndexOfMismatch(maybePalindrome)==-1) {
return s.length()-mismatchIndex-1;
}
// option 3 - removing one char is not enough to make this into a palindrome
return -1;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Palindrome Index
You are viewing a single comment's thread. Return to all comments →
// java solution
private static int findIndexOfMismatch(String s) { for(int i=0 ; i