125 Valid Palindrome


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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容