I'm writing a program that determines if a string is a palindrome recursively. I've decided to try and use regex, but I'm having a bit of trouble understanding the syntax. What I need to do is compare the first and last char to see if they are identical. How can I go about doing this?
Thanks!
解决方案
Yes, you can determine using regex if the first and last characters are the same:
str.matches("(.).*\\1")
This uses a "back reference" to refer to "group 1", which captures the first character.
Example:
"aba".matches("(.).*\\1") // true
"abc".matches("(.).*\\1") // false
You could then recursively remove the first and last characters and check again:
public static boolean isPalindrome(String str) {
return str.length() < 2 ||
(str.matches("(.).*\\1") && isPalindrome(str.substring(1, str.length() - 1)));
}