Lecture Videos
  1  import java.util.Scanner;
  2  
  3  public class PalindromeIgnoreNonAlphanumeric {
  4    /** Main method */
  5    public static void main(String[] args) {
  6      // Create a Scanner
  7      Scanner input = new Scanner(System.in);
  8  
  9      // Prompt the user to enter a string
 10      System.out.print("Enter a string: ");
 11      String s = input.nextLine();
 12  
 13      // Display result
 14      System.out.println("Ignoring non-alphanumeric characters, \nis "
 15        + s + " a palindrome? " + isPalindrome(s));
 16    }
 17  
 18    /** Return true if a string is a palindrome */
 19    public static boolean isPalindrome(String s) {
 20      // Create a new string by eliminating non-alphanumeric chars
 21      String s1 = filter(s);
 22  
 23      // Create a new string that is the reversal of s1
 24      String s2 = reverse(s1);
 25  
 26      // Compare if the reversal is the same as the original string
 27      return s2.equals(s1);
 28    }
 29  
 30    /** Create a new string by eliminating non-alphanumeric chars */
 31    public static String filter(String s) {
 32      // Create a string builder
 33      StringBuilder stringBuilder = new StringBuilder();
 34  
 35      // Examine each char in the string to skip alphanumeric char
 36      for (int i = 0; i < s.length(); i++) {
 37        if (Character.isLetterOrDigit(s.charAt(i))) {
 38          stringBuilder.append(s.charAt(i));
 39        }
 40      }
 41  
 42      // Return a new filtered string
 43      return stringBuilder.toString();
 44    }
 45  
 46    /** Create a new string by reversing a specified string */
 47    public static String reverse(String s) {
 48      StringBuilder stringBuilder = new StringBuilder(s);
 49      stringBuilder.reverse(); // Invoke reverse in StringBuilder
 50      return stringBuilder.toString();
 51    }
 52  }