ITeye博客

Valid Palindrome

KickCode · 2016-02-11 01:57 · Leetcode · 编程语言 · Markdown

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.

判断一个字符串是否为回文字符串,字符串中包含标点还有大小写的字母,我们可以先将字符串转换一下,用replaceAll方法去掉不用比较的字符,如何保留需要比较的字符我们用到正则表达式,处理之后在进行判断。代码如下:


public class Solution {
    public boolean isPalindrome(String s) {
        if(s == null) return true;
        String ss = s.replaceAll("[^0-9a-za-z]","").toLowerCase();
        return isPalin(ss);
    }
    public boolean isPalin(String s) {
        int l = 0;
        int r = s.length() - 1;
        while(l < r) {
            if(s.charAt(l) != s.charAt(r))
                return false;
            l ++;
            r --;
        }
        return true;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。