美文网首页
125 Valid Palindrome

125 Valid Palindrome

作者: yangminz | 来源:发表于2018-07-28 22:20 被阅读7次

    title: Valid Palindrome
    tags:
    - valid-palindrome
    - No.125
    - simple
    - string
    - regular


    Description

    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.

    Example 1:

    Input: "A man, a plan, a canal: Panama"
    Output: true
    

    Example 2:

    Input: "race a car"
    Output: false
    

    Corner Cases

    • ""
    • "a"
    • ","

    Solutions

    Regular Expression

    Use regular expression to filter any non-target characters and replace CAPTIAL CHARACTERS with lower ones. Then verify the palindrome as before.

    The running time is O(n) for the verification part.

    class Solution {
        public boolean isPalindrome(String s) {
            s = s.toLowerCase();
            s = s.replaceAll("[^a-z0-9]", "");
            if (s.equals("")) {return true;}
            boolean flag = true;
            int     len  = s.length();
            for (int i=0; i<len/2+1; i++) {
                flag = flag && (s.charAt(i) == s.charAt(len-i-1));
            }
            return flag;
        }
    }
    

    相关文章

      网友评论

          本文标题:125 Valid Palindrome

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