-5

Please use the method below.

I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.

I can't figure it out.

public static void main(String[] args) {


        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();


        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);


        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```

ZackCase
  • 41
  • 5

2 Answers2

0

You can have two indices i and j, where i starts at 0-index and j starts at the end of array. Do i++ and j-- and at each iteration check if the element is same and when j>i you break the loop and say its palindrome or else it is not Palindrome.

You can do this iteratively or recursively.

Hope it helps!

rootkonda
  • 1,700
  • 1
  • 6
  • 11
0

First, you can combine all of your regular expressions into one (first make the input lowercase, then eliminate everything not a lowercase letter). Second, you can eliminate building a temporary String to check if it's a palindrome; because you can iterate the characters in the word and check the front with the back. Like,

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
boolean palindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
    if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (!palindrome) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}

If you decide you want to reverse word anyway for a less efficient implementation. Use StringBuilder, because it can be done in one line (and I think it looks more readable).

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
if (!new StringBuilder(word).reverse().toString().equals(word)) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249