LeetCode 125 Valid Palindrome

题目描述

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.

分析

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

代码

    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');

    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50108139
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞