Java code to determine if a sentence reads the same backward or forward

A palindrome is a word, phrase, verse, or sentence that reads the same backward or forward. For example “race car”, “stack cats”.

Here’s the Java code to determine if a sentence reads the same backward or forward.

[cc lang=java]
import java.util.Stack;

public class Palindrome {
public static boolean isPalindrome(String str) {
boolean isPalindrome = true;
String sentence = str.replaceAll(“[\\P{L}+]”, “”);
char[] array = sentence.toCharArray();
Stack stack = new Stack();
for (int i = 0; i < array.length/2; i++) { stack.push(array[i]); } int counter = array.length/2; if (array.length % 2 == 1) { counter++; } while (!stack.isEmpty()) { char c = Character.toLowerCase((char) stack.pop()); if (Character.toLowerCase(array[counter++]) != c) { isPalindrome = false; break; } } return isPalindrome; } public static void main(String[] args) { System.out.println(isPalindrome("Noel sees Leon.")); } } [/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *