问题
I have a issue with my palindrome checker as it is not working properly. It must be able to test these 4 things:
TestPalindrome("Madam, I'm Adam", true);
TestPalindrome("addbda", false );
TestPalindrome("", false);
TestPalindrome("Dammit, I'm mad", true);
This is my code for the palindrome:
public static boolean IsPalindrome( String inputString )
{
String reverse = "";
for(int i = inputString.replaceAll("[^a-zA-Z ]", "").length() -1; i>=0; i--){
reverse = reverse + inputString.replaceAll("[^a-zA-Z ]", "").charAt(i);
}
if(inputString.replaceAll("[^a-zA-Z ]", "").equalsIgnoreCase(reverse.toString()) && !inputString.replaceAll("[^a-zA-Z ]", "").isEmpty()){
return true;
}
if(!inputString.replaceAll("[^a-zA-Z ]", "").equalsIgnoreCase(reverse.toString()) && !inputString.replaceAll("[^a-zA-Z ]", "").isEmpty()){
return false;
}
if(inputString.replaceAll("[^a-zA-Z ]", "").isEmpty()){
return false;
}
else return true;
}
}
This is what my output is:
TestPalindrome failed: expected true got false
TestPalindrome passed!
TestPalindrome passed!
TestPalindrome failed: expected true got false
Can anyone help me fix this so I get all passes in the list. I understand similar questions have been asked but I´m not asking how to do a palindrome checker but how to fix my specific one. I used those other questions to learn but for some reason my one doesn't work.
回答1:
In order to such algorithm to work you need to consider to clean the punctual symbols like comma, semmicolon, aposthrofs etc (am talking about ';:' etc)
Java has a StringBuilder
class and in there is a method to reverse strings
so if you clean the String to check, reverse it and compare it again itself you can see if it a palindrome or not...
Example:
public static void main(String[] args) {
String word = "Madam, I'm Adam";
String word2 = "addbda";
String word3 = "";
String word4 = "Dammit, I'm mad";
System.out.println(IsPalindrome(word));
System.out.println(IsPalindrome(word2));
System.out.println(IsPalindrome(word3));
System.out.println(IsPalindrome(word4));
}
private static boolean IsPalindrome(String word) {
String wordClean = word.replaceAll("[^a-zA-Z ]", "");
String reversedWord = new StringBuilder(wordClean).reverse().toString();
System.out.println(wordClean);
System.out.println(reversedWord);
return reversedWord.equalsIgnoreCase(wordClean)&&!wordClean.isEmpty();
}
this will print
MadamImAdam madAmImadaM true
addbda adbdda false
false (empty check)
DammitImmad dammItimmaD true
回答2:
You are not removing spaces, so only strings with spaces in the same places are good. Just use [^a-zA-Z]
against [^a-zA-Z ]
来源:https://stackoverflow.com/questions/36534673/java-palindrome-checker