回文测试 - 如何使案例不敏感?

时间:2015-02-06 20:37:47

标签: java recursion palindrome

我的代码将测试回文,但如果有任何标点符号,空格或字母不是相同的情况,则返回false。有谁知道如何让我的代码忽略大小写和标点符号?谢谢!

public class PalindromeDetector
{
    public static void main(String[] args)
    {
        String s;
        Scanner kb = new Scanner(System.in);

        System.out.println("Please enter a phrase you wish to " +
                           " test to discover if it it a palindrome: ");
        s = kb.nextLine();

        if (palTest(s))
        System.out.println("Your phrase is a palindrome!");
        else
        System.out.println("Your phrase is not a palindrome.");

    }

    /**
    The palTest method will determine whether or not
    a phrase is a palindrome.
    @param str The phrase which will be tested.
    @return True/False whether or not the phrase was a
            palindrome.
    */
    public static boolean palTest(String str)
    {

        char first = str.charAt(0);
        char last = str.charAt(str.length() - 1);

        if (str.length() <= 2)
            return true;
        else if (first != last)
            return false;
        else
            return palTest(str.substring(1, str.length()-1));
    }
}

2 个答案:

答案 0 :(得分:1)

如果您只是进行测试,可以在将字符串传递给函数之前对其进行规范化,例如

palTest(s.toLowerCase(Locale.ENGLISH).replaceAll("\\W",""))

\W是所有非单词字符的正则表达式字符类 - 此处的定义为:Character classes

答案 1 :(得分:1)

如何使用StringBuilder#reverse

String m = s.replaceAll("\\p{P}", "");
StringBuilder sb = new StringBuilder(m);
String reversed = sb.reverse().toString();

// By using equalsIgnoreCase, you ignore the case and don't need toLowerCase()
return m.equalsIgnoreCase(reversed);