Skip to content

Instantly share code, notes, and snippets.

@stephenorem
Created February 5, 2018 19:08
Show Gist options
  • Save stephenorem/3d1ae1835ffbf6014cd923995ff0e4f9 to your computer and use it in GitHub Desktop.
Save stephenorem/3d1ae1835ffbf6014cd923995ff0e4f9 to your computer and use it in GitHub Desktop.
evaluate whether or not a string is a palindrome; for example, 'red rum, sir, is murder'
/*
* Palindrome
*/
package palindrome;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Palindrome {
public static void main(String[] args) {
System.out.println("enter a string");
Scanner scanner = new Scanner(System.in);
String phrase = scanner.nextLine();
String palindrome = isPalindrome(phrase) ? "" : "NOT ";
System.out.println("Phrase IS " + palindrome + "a palindrome");
}
public static boolean isPalindrome(String phrase) {
phrase = phrase.toLowerCase().replaceAll("[^a-zA-Z0-9]","");
String revPhrase = new StringBuilder(phrase).reverse().toString();
return phrase.equals(revPhrase);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment