2

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!

EDIT: I found this helpful: AirSource Ltd's answer to Degvik's question

Community
  • 1
  • 1
faeophyta
  • 323
  • 5
  • 16
  • 3
    Instead of us writing the code, how about if you write it and test it and then ask questions if you have a problem. Okay? – stark Sep 19 '12 at 00:29
  • You should take a look at the tutorials before asking this sort of question: http://docs.oracle.com/javase/tutorial/essential/regex/ and http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html – sorifiend Sep 19 '12 at 00:33
  • I believe testing for a palindrome is impossible to do with a regular expression. http://stackoverflow.com/questions/233243/how-to-check-that-a-string-is-a-palindrome-using-regular-expressions – driangle Sep 19 '12 at 00:34
  • Regular expressions can be used to solve a lot of problems in very elegant manners. This, however, is none of them. You would solve this much easier and more elegantly with a for loop with two calls to String.charAt(). – Philipp Sep 19 '12 at 00:38
  • @stark I was not asking for code, I was merely asking about the theory, i.e., is it possible? – faeophyta Sep 19 '12 at 00:39

2 Answers2

3

There's really no need to use regular expressions if you want to work recursively here, and no need to use them if you want to test for palindromes in general (if it's even possible). You can try something like this:

public static boolean isPalindrome(String s) {
    if (s.length() < 2) return true;
    return s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1, s.length() - 1));
}
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • I already wrote it recursively, but I just wanted to see if it's possible to write it using `regex`. – faeophyta Sep 19 '12 at 00:37
  • Oh I see, I was under the impression that you wanted to use regexs in conjunction with recursion. According a links in one of the comments on your post, it's impossible (or at least damn difficult) to use regular expressions to test for palindromes. – arshajii Sep 19 '12 at 00:39
3

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)));
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722