package examples;
/**
* This class represents a single sentence. It is based on an example from
* section 13.2 of Horstmann's Big Java, 3rd ed.
*
* @author Cay Horstmann
*/
public class Sentence
{
private final String text;
/**
* Creates a sentence object for the given string.
*
* @param text
*/
public Sentence(String text)
{
this.text = text;
}
/**
* Main entry point for example.
*
* @param args
* ignored
*/
public static void main(String[] args)
{
String str = "Go hang a salami, I'm a lasagna hog.";
Sentence sent = new Sentence(str);
System.out.println(sent.isPalindrome());
}
/**
* Checks whether this sentence is a palindrome. Palindromic sentences are
* considered to be those the read the same forward or backward, ignoring
* case, punctuation, and spaces.
*
* Examples:
*
* new Sentence("deified");
*
* new Sentence("I prefer Pi");
*
* new Sentence("A man, a plan, a canal -- Panama!");
*
* new Sentence("Madam, I'm Adam");
*
* new Sentence("Go hang a salami, I'm a lasagna hog.");
*
* @return true iff this sentence is a palindrome
*/
public boolean isPalindrome()
{
return this.isPalindrome(0, this.text.length() - 1);
}
/**
* Checks whether this sentence is a palindrome. Palindromic sentences are
* considered to be those the read the same forward or backward, ignoring
* case, punctuation, and spaces. (recursive helper)
*
* @param start
* @param end
* @return true or false if the first/last letters match
*/
public boolean isPalindrome(int start, int end)
{
int length = end - start + 1;
if (length < 1)
{
return true;
}
char first = Character.toLowerCase(this.text.charAt(start));
char last = Character.toLowerCase(this.text.charAt(end));
boolean firstIsValid = Character.isLetter(first);
boolean lastIsValid = Character.isLetter(last);
if (firstIsValid && lastIsValid)
{
if (first == last)
{
return this.isPalindrome(start + 1, end - 1);
}
else
{
return false;
}
}
if (!firstIsValid)
{
return this.isPalindrome(start + 1, end);
}
if (!lastIsValid)
{
return this.isPalindrome(start, end - 1);
}
System.out.println("Shouldn't get here.");
return false;
}
/**
* @return a NEW sentence object whose text is the reverse of this one
*/
public Sentence reverse()
{
return this.reverse(this.toString());
}
/**
* @param string
* @return a NEW sentence object with the last character at the end
*/
public Sentence reverse(String string)
{
if (string.length() <= 1)
{
return new Sentence(string);
}
else
{
String endChar = string.substring(string.length()-1,string.length());
String restOfString = string.substring(0, string.length() -1);
return new Sentence(endChar + this.reverse(restOfString));
}
}
@Override
public String toString()
{
return this.text;
}
}