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

LeetCode: Valid Palindrome [125]

作者头像
全栈程序员站长
发布2022-07-14 18:05:05
1430
发布2022-07-14 18:05:05
举报

大家好,又见面了,我是全栈君

【题目】

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.

【题意】

给定一个字符串,仅仅关注英文字母和数字,忽略其它字符。问英文字母和数字按序排列后是否构成是回文

【思路】

利用回文串推断的老办法就可以,两个指针p1, p2分别从头和尾中间扫描,推断对称位置的字符是否同样,仅仅只是须要跳过除英文字母和数字之外的其它字符。 另外还须要注意处理2中特殊情况:(1)字符串为空串,(2)字符串不是空串,但里面没有英文字母或者数字。 这两种情况都判定为true

【代码】

代码语言:javascript
复制
class Solution {
public:
    bool isAlphanumeric(char c){
        if(isdigit(c))return true;
        if(c>='A'&&c<='Z'||c>='a'&&c<='z')return true;
        return false;
    }
    
    bool isEqual(char c, char b){
        if(isdigit(c))return c==b;
        if(c>='A'&&c<='Z')c='a'+(c-'A');
        if(b>='A'&&b<='Z')b='a'+(b-'A');
        return c==b;
    }

    bool isPalindrome(string s) {
        int len=s.length();
        if(len==0)return true;
        
        int front=0;
        int back=len-1;
        while(front<back){
            while(front<=back && !isAlphanumeric(s[front]))front++;
            while(front<=back && !isAlphanumeric(s[back]))back--;
            if(front<=back){
                if(!isEqual(s[front], s[back]))return false;
                front++;
                back--;
            }
        }
        return true;
    }
};

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117906.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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