Leetcode-字符串-125

125. Valid Palindrome

题目链接

Given a string, determine if it is a palindrome(回文), considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.

Input : “A man, a plan, a canal: Panama”
Output : true

判断字符串是否为回文序列

方法1:5ms

设置前后指针head、tail
Java Character类
java.lang.Character.isLetter(); 断定指定字符是否是一个字母。
java.lang.Character.isDigit(); 断定指定字符是否是一个数字。
java.lang.Character.isLetterOrDigit(); 断定指定字符是否是一个数字或字母。

public boolean isPalindrome(String s) {
        char[] words = s.toLowerCase().toCharArray();
        int i = 0, j = words.length - 1;
        while (i < j) {
            while (!Character.isLetterOrDigit(words[i]) && i < j) i++;  //如果不加 i<j,比如 ".," 会报错数组越界
            while (!Character.isLetterOrDigit(words[j]) && i < j) j--;
            if (words[i] != words[j])
                return false;
            i++;
            j--;
        }
        return true;
}


方法2:21ms 虽然简洁,但是比较慢

使用字符串的正则匹配,将字母数字以外的字符全替换为空,然后只需判断新字符串与其反转的字符串是否相同

replaceAll() 方法使用给定的参数 replacement 替换字符串中所有匹配给定正则表达式 regex 的子字符串。

public String replaceAll (String regex, String replacement)
regex –匹配此字符串的正则表达式。 newChar – 用来替换每个匹配项的字符串。

[^xyz] 反向字符集。该正则表达式语法匹配未包含的字符。例如,”[^abc]”匹配”plain”中”p”,”l”,”i”,”n”。

public boolean isPalindrome2(String s) {
        s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        String rev = new StringBuilder(s).reverse().toString();
        return s.equals(rev);
}


猜你喜欢

转载自blog.csdn.net/gaoruowen1/article/details/80978660
今日推荐