问题
Hey I could use a little bit of help to figure out why my program isn't working. The question is to make a program using recursion that figures if it the text given is a palindrome or not after all the punctuation and white spaces are removed. While the program so far compiles, it returns every value as false. We are only allowed to change the isSymmetrical method. I could use whatever help possible trying to figure out how to make this work. Thank you.
public class StringSymmetry {
public static boolean isSymmetrical(String inputText)
{
if(inputText.length() == 0 || inputText.length() ==1)
return true;
if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
return isSymmetrical(inputText.substring(1,inputText.length()-1));
return false;
}
public static void main(String[] args) {
String[] sampleData =
{ "Don't nod",
"Dogma: I am God",
"Too bad - I hid a boot",
"Rats live on no evil star",
"No trace; not one carton",
"Was it Eliot's toilet I saw?",
"Murder for a jar of red rum",
"May a moody baby doom a yam?",
"Go hang a salami; I'm a lasagna hog!",
"Name is Bond, James Bond"
};
for (String s : sampleData)
{
System.out.println("isSymmetrical (" + s + ") returns " + isSymmetrical(s));
}
}
}
回答1:
The problem is that you didn't include any checks for case or punctuation and white space.
One way you could do it is something like this. The specifics depend on what you're allowed to use for the assignment, but you're probably intended to do something along these lines.
Also, note that toLowerCase
is problematic if you have the default locale set to something unusual like Turkey. For proper robustness, you need to specify a locale, but this isn't something you'll have to worry about in a homework assignment.
public static boolean isSymmetrical(String inputText)
{
inputText = inputText.toLowerCase();
if(inputText.length() == 0 || inputText.length() ==1)
return true;
if(!Character.isLetter(inputText.charAt(0)))
return isSymmetrical(inputText.substring(1,inputText.length()));
if(!Character.isLetter(inputText.charAt(inputText.length()-1)))
return isSymmetrical(inputText.substring(0,inputText.length()-1));
if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
return isSymmetrical(inputText.substring(1,inputText.length()-1));
return false;
}
来源:https://stackoverflow.com/questions/16258877/string-symmetry-program