Saturday 21 November 2015

Palindrome



palindrome is a word, phrasenumber, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers. Famous examples include "A man, a plan, a canal, Panama!", "Amor, Roma", "race car", "stack cats", "step on no pets", "taco cat", "put it up", "Was it a car or a cat I saw?" and "No 'x' in Nixon"


Java code to validate the Palindrome is as follow : 

/*
 * @sachin
 */
public class Palindrome {
public static boolean isPalindrome(String input) throws Exception{
if(input == null || input.isEmpty()) {
throw new Exception("Invalid input");
}
String str = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
boolean isPalindrome = true;
int i = 0;
int j = str.length();
for(i=0; i< j;i++){
if(str.charAt(i) == str.charAt(j-1)){
j--;
continue;
} else {
isPalindrome = false;
}
}
return isPalindrome;
}
public static void main(String[] args) {
try {
System.out.println("isValidPalindrome=" + isPalindrome("No 'x' in Nixon"));
                        System.out.println("isValidPalindrome=" + isPalindrome("12321"));
                        System.out.println("isValidPalindrome=" + isPalindrome("sachin"));
} catch (Exception e) {
e.printStackTrace();
}
}

}

Output

true
true
false

No comments:

Post a Comment