LeetCode: Valid Palindrome [125]

LeetCode: Valid Palindrome [125]

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

LeetCode: Valid Palindrome [125]此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“”,获取验证码。在微信里搜索“”或者“”或者微信扫描右侧二维码都可以关注本站微信公众号。

【题目】

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
    

【代码】

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;
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号