前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Valid Palindrome

Leetcode: Valid Palindrome

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 17:23:12
3280
发布2019-01-22 17:23:12
举报

题目: 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.

思路分析: 将字符串中的非数字字母字符跳过,大写全部转小写,然后从字符串两头向中间逼近,逐一进行比较。

C++参考示例:

class Solution
{
private:
    bool isAlphanumeric(char &ch)
    {
        if (ch >= 'A' && ch <= 'Z')
        {
            ch += 32;
            return true;
        }
        if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'))
        {
            return true;
        }
        return false;
    }

public:
    bool isPalindrome(string s)
    {
        size_t length = s.length();
        if (length <= 1)
        {
            return true;
        }

        size_t i = 0;
        size_t j = length - 1;
        while (i < j)
        {
            if (!isAlphanumeric(s[i]))
            {
                i++;
                continue;
            }
            if (!isAlphanumeric(s[j]))
            {
                j--;
                continue;
            }
            if (s[i] != s[j])
            {
                return false;
            }
            i++;
            j--;
        }

        return true;
    }
};

晒账截图!突然发现原来C#要比Java快这么多!

回文算法提交结果
回文算法提交结果
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档