Palindromes A palindrome is a word or sentence that reads the same forwards as i
ID: 3882147 • Letter: P
Question
Palindromes A palindrome is a word or sentence that reads the same forwards as it does backwards. Letter case and punctuation are always ignored. Spaces are ignored in strict" ones. "ordinary" palindromes but not in racecar a word that is a palindrome a “strict" palindrome (spaces Able was I, ere I saw Elba! count) attributed to Napoleon. A man, a plan, a canal: Panama! an"ordinary palindrome; spaces are ignored. 2445442 a palindromic number. There are lots of ways to see if a String is or is not a palindrome What would be a recursive algorithm to determine whether or not a String is a palindrome? Write a program that performs the following tasks: Display a friendly greeting to the user. Prompt the user for an input String. Accept that String. Determine whether or not that String is a palindrome by calling a recursive function. If so, classify the result as ordinary" or "strict." Display the result. The input String can contain any anything at all, but consider only alphanumeric characters (that is, strip out punctuation, and any special characters) and ignore letter case. Spaces are ignored in "ordinary" palindromes and considered in "strict" palindromes.Explanation / Answer
Please find my implementation.
public class MyPalindrome {
public static boolean isPalindrome(String str){
if(str == null)
return true;
int j= str.length()-1;
int i= 0;
while(i < j){ // traversing from front and back side
char iChar = str.charAt(i);
char jChar = str.charAt(j);
if(!Character.isDigit(iChar) && !Character.isLetter(iChar)) // if not digit or letter, skip from front
i++;
else if(!Character.isDigit(jChar) && !Character.isLetter(jChar)) // if not digit or letter, skip from back
j--;
else{
if(Character.isLetter(iChar) && Character.isLetter(jChar)){ // if both are letter, then compare after ignoring case
if(Character.toLowerCase(iChar) != Character.toLowerCase(jChar))
return false;
}
else{
if(iChar != jChar)
return false;
}
i++;
j--;
}
}
//reached here means: string is palindrome
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("Too hot to hoot"));
System.out.println(isPalindrome("Lisa Bonet ate no basil Warsaw was raw"));
}
}
/*
Sampel run:
true
false
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.