RosettaCodeData/Task/Palindrome-detection/Processing/palindrome-detection-2.proc...

40 lines
1.1 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

void setup(){
println("PalindromeDetection");
String[] tests = {
"abcba",
"aa",
"a",
"",
" ",
"ab",
"abcdba",
"A man, a plan, a canal: Panama!",
"Dammit, Im Mad!",
"Never odd or even",
"ingirumimusnocteetconsumimurigni"
};
for (int i = 0; i < tests.length; i++){
println((i + 1) + ". '" + tests[i] + "' isExactPalindrome: " + isExactPalindrome(tests[i]) + " isInexactPalindrome: " + isInexactPalindrome(tests[i]));
}
}
/*
* Check for exact palindrome using StringBuilder and String since String in Java does not provide any reverse functionality because Strings are immutable.
*/
boolean isExactPalindrome(String s){
StringBuilder sb = new StringBuilder(s);
return s.equals(sb.reverse().toString());
}
/*
* Check for inexact palindrome using the check for exact palindromeabove.
*/
boolean isInexactPalindrome(String s){
// removes all whitespaces and non-visible characters,
// remove anything besides alphabet characters
// ignore case
return isExactPalindrome(s.replaceAll("\\s+","").replaceAll("[^A-Za-z]+", "").toLowerCase());
}