Check if a string is a palindrome

Description: A palindrome reads the same from both sides, like madam. Write isPalindrome(String s) which ignores the case and the spaces. Test it with “Madam”, “Nurses run” and “Java”.

Hint:

  • Clean the text with replace(" ", "") and toLowerCase(), then compare it with its reverse.

Solution

public class Main {
    static boolean isPalindrome(String s) {
        String clean = s.replace(" ", "").toLowerCase();
        String reversed = new StringBuilder(clean).reverse().toString();
        return clean.equals(reversed);
    }

    public static void main(String[] args) {
        for (String text : new String[]{"Madam", "Nurses run", "Java"}) {
            System.out.println(text + " -> " + isPalindrome(text));
        }
    }
}
Output

Madam -> true
Nurses run -> true
Java -> false

How it works

  • We remove the spaces and use one case, so only the letters are compared.
  • equals() compares the text. Do not use ==.

Read Java Strings.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.