package palindrome;
import java.util.*;
public class TestPalindrome
{
public TestPalindrome()
{
}
public static boolean isPalindrome(String word) {
int left = 0; // index of leftmost unchecked char
int right = word.length() -1; // index of the rightmost
while (left < right) { // continue until they reach center
if (word.charAt(left) != word.charAt(right)) {
return false; // if chars are different, finished
}
left++; // move left index toward the center
right--; // move right index toward the center
}
return true; // if finished, all chars were same
}
public static void main(String[] args)
{
TestPalindrome testPalindrome = new TestPalindrome();
String s = "Was it a rat I saw?" ;
s = s.replaceAll("[\\s\\p{Punct}]", "").toLowerCase();
boolean flag = isPalindrome(s);
System.out.println(s + " PALINDROME ? " + flag);
}
}
No comments:
Post a Comment