2

我正在编写一个程序来确定字符串是否是递归回文。我决定尝试使用正则表达式,但我在理解语法时遇到了一些麻烦。我需要做的是比较第一个和最后一个字符,看看它们是否相同。我该怎么做呢?

谢谢!

编辑:我发现这很有帮助:AirSource Ltd 对 Degvik 问题的回答

4

2 回答 2

3

是的,如果第一个字符和最后一个字符相同,您可以确定使用正则表达式:

str.matches("(.).*\\1")

这使用“反向引用”来引用“组 1”,它捕获第一个字符。

例子:

"aba".matches("(.).*\\1") // true
"abc".matches("(.).*\\1") // false

然后,您可以递归删除第一个和最后一个字符并再次检查:

public static boolean isPalindrome(String str) {
    return str.length() < 2 || 
        (str.matches("(.).*\\1") && isPalindrome(str.substring(1, str.length() - 1)));
}
于 2012-09-19T01:03:56.317 回答
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));
}
于 2012-09-19T00:31:19.537 回答