美文网首页
Valid Palindrome

Valid Palindrome

作者: nafoahnaw | 来源:发表于2018-03-06 11:51 被阅读0次

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

判断给出的字符串是否是回文
自己的思路如下,正则表达式格式化给出的字符串,使用StringBuilder.reverse()方法得到反转的字符串,如果与格式化后的字符串一致,那么返回true,否则返回false

   public boolean isPalindrome(String s) {
        if(s == null){
            return false;
        }
        s = s.replaceAll("\\W+", "").toLowerCase();
        if(s.isEmpty()){
            return true;
        }
        return s.equals(new StringBuilder(s).reverse().toString());
   }

这种用到了java本身提供的特性,还有一种办法是首指针++,尾指针--,并判断s[i]==s[j]

    public boolean isPalindrome(String s) {
        if (s == null) {
            return false;
        }
        s = s.toLowerCase();
        for(int i = 0, j = s.length() - 1; i < j;){
            if(!Character.isLetterOrDigit(s.charAt(i))){
                i++;
            }else if(!Character.isLetterOrDigit(s.charAt(j))){
                j--;
            }else{
                if(s.charAt(i++) != s.charAt(j--)){
                    return false;
                }
            }
        }
        return true;
    }

相关文章

网友评论

      本文标题:Valid Palindrome

      本文链接:https://www.haomeiwen.com/subject/urplfftx.html