-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeChecker.java
More file actions
37 lines (33 loc) · 1.17 KB
/
PalindromeChecker.java
File metadata and controls
37 lines (33 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package module4.recursion.palindromes;
/**
* PalindromeChecker
*
* @author Mae Morella
*/
public class PalindromeChecker {
/**
* Detects palindromes using a recursive method.
* A palindrome is any string whose letters are the same forward as they are backwards.
* Non-alphanumeric characters are ignored; for example, {@code "Madam I'm adam"} is
* converted to {@code "madamimadam"}, and considered a valid palindrome.
*
* @param str The string to test
* @return If the string is a valid palindrome, {@code true}. Otherwise
* {@code false}
*/
public static boolean isPalindrome(String str) {
String cleanString = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
return isPalindromeRecursive(cleanString);
}
private static boolean isPalindromeRecursive(String str) {
if (str.length() < 2) return true;
char first = str.charAt(0);
char last = str.charAt(str.length() - 1);
if (first == last) {
String inner = str.substring(1, str.length() - 1);
return isPalindromeRecursive(inner);
} else {
return false;
}
}
}