/* Copyright (c) 2006 L. Searchwell. */ //import java.io.*; import java.lang.Character; //import java.lang.StringBuffer; public class Palindrome { private String raw_input_str = null, working_str = null; public boolean IGNORE_PUNCTUATION; Palindrome() { this(null); } Palindrome(String str) { this.raw_input_str = (str != null ? str : ""); this.IGNORE_PUNCTUATION = true; } public void setString(String str) { this.raw_input_str = (str != null ? str : ""); } public String getInputString() { return this.raw_input_str; } public String getDepuntuatedString() { return this.working_str; } private boolean palindrome(String str, int position) { /*int odd*/; if(str == null) return false; if((position < 0) || (position > str.length())) //Should not be > position = 0; //System.out.print(position); if(str.length() == 0) { return false; } else if(str.length() == 1) { //System.out.println("That is a palindrome! [" + position + "/" + // (str.length()-1) + "]"); return true; } if(str.charAt(position) == str.charAt(str.length() - 1 - position)) { if((str.length() % 2) > 0) { /* Of odd length */ if(position == (str.length() - 2)) { //System.out.println("\nThat is a palindrome!\n[ " + str + " ]"); return true; } } else { /* Of even length */ if(position == (str.length() - 1)) { //System.out.println("\nThat is a palindrome!\n[ " + str + " ]"); return true; } } return palindrome(str, (position + 1)); } else { //System.out.println("\nThat is not a palindrome!"); //for(int i = 0; i < str.length(); i++) // if((i == position) || (i == (str.length() - 1 - position))) // System.out.print("[" + str.charAt(i) + "]"); // else // System.out.print(str.charAt(i)); //System.out.println(); } return false; } public String removePuntuation(String str) { int i, j; if(str != null) { char charr[] = new char[str.length()]; for(i = 0, j = 0; i < str.length(); i++) { if(Character.isLetterOrDigit(str.charAt(i))) { charr[j] = str.charAt((i)); j++; } } //System.out.println("Pre-Length: " + str.length() +" to be "+ j +" "+ str); str = String.copyValueOf(charr, 0 , j); //System.out.println("Post-Length: " + str.length() +" to be "+ j +" "+ str); } else { str = ""; } this.working_str = str; return str; } public boolean check(String str) { //System.out.println("Depuntuate?: " + this.IGNORE_PUNCTUATION); this.raw_input_str = (str != null ? str : ""); //Store for getString(). if(str == null) return false; if(this.IGNORE_PUNCTUATION) str = removePuntuation(str); else this.working_str = this.raw_input_str; //System.out.println("Depuntuated: " + str); //Replaced by getDepuntuatedString() str = str.toLowerCase(); return palindrome(str, 0); } }