[125] Valid Palindrome

1. 题目描述

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.

题目大意为判断一个由数字、字母组成的字符串是否是回文,且可能包含其他字符,判断时可直接忽略。

2. 解题思路

设置两个指针,一个从前往后移动,一个从后往前移动,每次移动到都是字母或数字的字符时,判断两个字符是否是相等的,如果不相等,返回false。如果相等继续比较,直到两个指针碰到一起或已经超过了回文中间的位置(j > i)。且当一个字母的时候肯定是回文,所以当i=j时不用做判断。
题目还给了一个小点,就是需要考虑当字符串为空的时候是不是一个回文,我没考虑这个问题,直接判断的字符串长度小于等于1是就为true。但实际上有可能要求输入为空时不是一个回文的。所以面试时如果碰到这个题目可以具体问一下面试官,也可以获得细心的印象分:)。

3. Code

public class Solution {
    public boolean isPalindrome(String s) {
        if(s.length() <= 1)
        {
            return true;
        }
        // 将字符串中的字母全都转换为小写字母
        s = s.toLowerCase();
        // 设置一个标记
        boolean flag = true;
        for(int i = 0, j = s.length()-1; i < j; ++i,--j)
        {
            // 当i不是字母时。注意判断位置越界!
            while (!isAlphanumeric(s.charAt(i)) && i < s.length()-1)
            {
                ++i;
            }
            // 当j不是字母时。注意判断位置越界!
            while(!isAlphanumeric(s.charAt(j)) && j > 0)
            {
                --j;
            }
            if (i < j)
            {
                // ij不相等,不是回文
                if(s.charAt(i) != s.charAt(j)) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    // 判断一个字母是否为字母或数字
    public boolean isAlphanumeric(char c)
    {
        return (c >= 'a' && c <='z') || (c >='0' && c<='9');
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值