I've been asked in class to determine whether a sentence string (ignoring the upper/lower cases, punctuations, and spaces) is a palindrome or not, and return true/false accordingly.
I've already had a look at several of the discussions here relating to palindrome strings, but I still can't seem to figure out what exactly is wrong with my code, especially because it works in some cases but not others.
In class sentence I have prive String mySentence and private int myNumWords. Regarding the static boolean isPalindrome, I was encouraged to try recursion but I thought to try iteration first.
//Constructor. Creates sentence from String str.
// Finds the number of words in sentence.
//Precondition: Words in str separated by exactly one blank.
public Sentence( String str )
{
mySentence = str;
int count = 0;
for(int k = 0; k<str.length(); k++)
{
if(str.substring(k,k+1).equals(" "))
count++;
}
myNumWords = count + 1;
}
public int getNumWords()
{
return myNumWords;
}
public String getSentence()
{
return mySentence;
}
//Returns copy of String s with all blanks removed.
//Postcondition: Returned string contains just one word.
private static String removeBlanks( String s )
{
return s.replaceAll(" ", "");
}
//Returns true if mySentence is a palindrome, false otherwise.
public boolean isPalindrome()
{
boolean palindrome = true;
String sentence = removeBlanks(mySentence);
String newsentence = removePunctuation(sentence);
int indice1 = 0;
int indice2 = newsentence.length() - 1;
while(indice1 < indice2)
{
if(newsentence.charAt(indice1)!= newsentence.charAt(indice2))
palindrome = false;
indice1++;
indice2--;
}
return palindrome;
}
//Precondition: s has no blanks, no punctuation, and is in lower case.
//Returns true if s is a palindrome, false otherwise.
private static boolean isPalindrome( String s, int start, int end )
{
boolean palindrome = true;
String sentence = removeBlanks(s);
String newsentence = removePunctuation(sentence);
int indice1 = 0;
int indice2 = newsentence.length() - 1;
while(indice1 < indice2)
{
if(newsentence.charAt(indice1)!= newsentence.charAt(indice2))
palindrome = false;
indice1++;
indice2--;
}
return palindrome;
}
//Returns copy of String s with all letters in lowercase.
//Postcondition: Number of words in returned string equals
// number of words in s.
private static String lowerCase( String s )
{
return s.toLowerCase();
}
//Returns copy of String s with all punctuation removed.
//Postcondition: Number of words in returned string equals
// number of words in s.
private static String removePunctuation( String s )
{
return s.replaceAll("\\p{Punct}", "");
}
For instance, for "A Santa lived as a devil at NASA" as my input, I'm supposed to get "true", but keep returning "false".