A palindrome reads the same backwards. Clean the text first, then compare.
What to build
A program that says whether each line is a palindrome.
Requirements
- For each line, ignore everything except letters and digits, and ignore case.
- Print
"LINE" is a palindromeor"LINE" is not a palindrome, with the line as it was read. - A line with no letters or digits is a palindrome.
Input
Line 1: n. Then n lines.
Output
n lines.
Constraints
1 ≤ n ≤ 50; lines have at most 200 characters.
Example
Input:
3
Racecar
A man, a plan, a canal: Panama!
Java
Output:
"Racecar" is a palindrome
"A man, a plan, a canal: Panama!" is a palindrome
"Java" is not a palindrome
Why it works
Cleaning first makes spaces, punctuation and case irrelevant, and equals compares the cleaned text with its reverse character by character.
Examples
Example 1 · Input
3 Racecar A man, a plan, a canal: Panama! Java
Expected output
"Racecar" is a palindrome "A man, a plan, a canal: Panama!" is a palindrome "Java" is not a palindrome
Example 2 · Input
1 12321
Expected output
"12321" is a palindrome
Hints
Hint 1
Keep only letters and digits, in lower case, then compare the string with its reverse.
Hint 2
new StringBuilder(text).reverse().toString() reverses a string.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
static String clean(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
for (int i = 0; i < n; i++) {
String line = in.nextLine();
String c = clean(line);
boolean yes = c.equals(new StringBuilder(c).reverse().toString());
System.out.println("\"" + line + "\" is " + (yes ? "a palindrome" : "not a palindrome"));
}
}
}