简体   繁体   English

如何检查排除非字母数字字符的回文?

[英]How to check for palindrome excluding the non-alphanumeric characters?

Here's the code that I attempted这是我尝试的代码

public String isPalindrome(String s) {


    String trimmed = s.replaceAll("[^A-Za-z0-9]", "");


    String reversed = "";

    int len = trimmed.length();


    for (int i = len - 1; i >= 0; i--) {

        char[] allChars = trimmed.toCharArray();

        reversed += allChars[i];

    }


    if (trimmed.equalsIgnoreCase(reversed)) {
        return "true";
    } else {
        return "false";
    }

}

Sample Input 1 A man, a plan, a canal: Panama示例输入 1 一个人、一个计划、一条运河:巴拿马

Sample Output 1 true样品 Output 1 真

Explanation 1 The given string is palindrome when considering only alphanumeric characters.解释 1 当只考虑字母数字字符时,给定的字符串是回文。

Sample Input 2 race a car示例输入 2 赛车

Sample Output 2 false样品 Output 2 假

Explanation 2 The given string is not a palindrome when considering alphanumeric characters.解释 2 在考虑字母数字字符时,给定的字符串不是回文。

You can return boolean instead of String :您可以返回boolean而不是String

public static boolean isPalindrome(String s) {
    String trimmed = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();

    int from = 0, to = trimmed.length() - 1;
    while (from < to) {
        if (trimmed.charAt(from) != trimmed.charAt(to)) {
            return false;
        }
        from++;
        to--;
    }
    return true;
}

You can use StringBuilder to reverse a String:您可以使用 StringBuilder 来反转字符串:

public static void main(String[] args) {
    String input = "a#b!b^a";
    String clean = input.replaceAll("[^A-Za-z0-9]", "");
    String reverse = new StringBuilder(clean).reverse().toString();
    boolean isPalindrome = reverse.equals(clean);
    System.out.println(isPalindrome);
}

Your variable len comes from the length of the String s .您的变量len来自 String s的长度。 But you use the value on the array coming from trimmed .但是您使用来自trimmed的数组上的值。

So if you want to remove the IndexOutOfBoundsException you should change your len declaration to:因此,如果您想删除IndexOutOfBoundsException ,您应该将len声明更改为:

int len = trimmed.length();

You can do like this in linear time as the loops are driven by the presence of non-alphabetic/digit characters.您可以在线性时间内执行此操作,因为循环是由非字母/数字字符的存在驱动的。 Also, no trimming or reversal of the string is required.此外,不需要对字符串进行修整或反转。

String[] test =  {"A man,  a plan, a canal: Panama",
         "race a car","foobar", "ABC2CEc2cba"};

for (String s : test) {
     System.out.printf("%5b -> %s%n", isPalindrome(s), s);
}

prints印刷

 true ->    A man,  a plan, a canal: Panama 
false -> race a car
false -> foobar
 true -> ABC2CEc2cba 

The outer while loop drives then entire process until the indices cross or are equal.外部 while 循环驱动整个过程,直到索引交叉或相等。 The inner loops simply skip over non-alphabetic/digit characters.内部循环只是跳过non-alphabetic/digit字符。

public static boolean isPalindrome(String s) {
    int k = s.length() - 1;
    int i = 0;
    char c1 = '#';
    char c2 = '#';
    while (i <= k) {
        while (!Character.isLetterOrDigit(c1 = s.charAt(i++)));
        while (!Character.isLetterOrDigit(c2 = s.charAt(k--)));
        if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
            return false;
        }
    }
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM