您的位置:首页 > 其它

LeetCode 125 Valid Palindrome

2015-11-30 09:21 363 查看

题目描述

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.

分析

注意忽略非字母数字的字符

代码

[code]    public static boolean isPalindrome(String s) {

        if (s.length() <= 1) {
            return true;
        }

        char[] chars = s.toLowerCase().toCharArray();

        for (int st = 0, ed = chars.length - 1; st <= ed; st++, ed--) {

            while (st < ed && !isValid(s, st))
                st++;
            while (st < ed && !isValid(s, ed))
                ed--;

            if (chars[st] != chars[ed])
                return false;

        }

        return true;
    }

    static boolean isValid(String s, int i) {

        char c = s.charAt(i);

        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')|| (c >= 'A' && c <= 'Z');

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: