40 lines
1.1 KiB
Text
40 lines
1.1 KiB
Text
|
|
void setup(){
|
|||
|
|
println("PalindromeDetection");
|
|||
|
|
|
|||
|
|
String[] tests = {
|
|||
|
|
"abcba",
|
|||
|
|
"aa",
|
|||
|
|
"a",
|
|||
|
|
"",
|
|||
|
|
" ",
|
|||
|
|
"ab",
|
|||
|
|
"abcdba",
|
|||
|
|
"A man, a plan, a canal: Panama!",
|
|||
|
|
"Dammit, I’m 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());
|
|||
|
|
}
|