首页 文章

如何使用正则表达式实现递归回文检查器? [关闭]

提问于
浏览
0

到目前为止,我一直在使用 ^[a-zA-Z]+( [a-zA-z]+)*$ 确保用户输入在开头和结尾没有空格,不接受数字或特殊字符,只接受字母字符 .

我在网上查看了正则表达式列表,在我的文本中,我无法在这些条件下为递归回文程序制定一个:

  • 接受包含大写或小写字符的字符串 .

  • 接受标点符号和单行间隔空格 .

在验证后我不认为我需要一个正则表达式,但如果有,我想知道它是什么 .

  • 验证后大写字母必须转换为小写字母 .

  • 标点符号和空格将被忽略 .

1 回答

  • 0

    如果我理解正确,你想在Java中创建一个使用正则表达式的递归回文检查器 . 我对学习Java感兴趣,所以我把它作为我自己的“家庭作业问题”,但它也可能是你的 .

    import java.lang.*;
    import java.util.*;
    import java.util.regex.*;
    
    class Main
    {
        public static boolean recursivePalindrome(String str)
        {
            // We need two patterns: one that checks the degenerate solution (a
            // string with zero or one [a-z]) and one that checks that the first and
            // last [a-z] characters are the same. To avoid compiling these two
            // patterns at every level of recursion, we compile them once here and
            // pass them down thereafter.
            Pattern degeneratePalindrome = Pattern.compile("^[^a-z]*[a-z]?[^a-z]*$", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Pattern potentialPalindrome  = Pattern.compile("^[^a-z]*([a-z])(.*)\\1[^a-z]*$", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            return recursivePalindrome(str, degeneratePalindrome, potentialPalindrome);
        }
    
        public static boolean recursivePalindrome(String str, Pattern d, Pattern p)
        {
            // Check for a degenerate palindrome.
            if (d.matcher(str).find()) return true;
    
            Matcher m = p.matcher(str);
    
            // Check whether the first and last [a-z] characters match.
            if (!m.find()) return false;
    
            // If they do, recurse using the characters captured between.
            return recursivePalindrome(m.group(2), d, p);
        }
    
        public static void main (String[] args) throws java.lang.Exception
        {
            String str1 = "A man, a plan, a canal... Panama!";
            String str2 = "A man, a pan, a canal... Panama!";
    
            System.out.println(str1 + " : " + Boolean.toString(recursivePalindrome(str1)));
            System.out.println(str2 + " : " + Boolean.toString(recursivePalindrome(str2)));
        }
    }
    

    输出是:

    A man, a plan, a canal... Panama! : true
    A man, a pan, a canal... Panama! : false
    

相关问题