In: Computer Science
Write a function that will take a string containing only alphanumeric characters that are in lowercase (if you think your logic requires you to use more than one argument, please go ahead). Your task is to see if the string becomes a palindrome if only one character is removed from anywhere in the string.
I did it in two functions to make easier to understand comment if you need modifications
static boolean isPalindrome(String str)
{
int i = 0, j = str.length() -
1;
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
public static void alphaNumericPalindrome(String str){
if (str.matches("^[a-z0-9]*$"))
{
for (int i = 0;i<str.length() ; i++){
String test =
str.substring(0,i)+str.substring(i+1,str.length());
if(isPalindrome(test)){
System.out.print("\n The String "+str+" becomes palindrome after
removing "+str.charAt(i)+"\n");
return;
}
}
System.out.print("\n The String "+str+" does not becomes palindrome
after removing one letter\n");
return;
}else{
System.out.print("String Contains non alphanumeric or lowercase
values");
}
}