加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

【LeetCode】125. Valid Palindrome

发布时间:2020-12-13 21:19:02 所属栏目:PHP教程 来源:网络整理
导读:问题描写 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 tha

问题描写

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.

回文字符串判断,但只判断字母和数字是不是构成回文字符串,标点符号被略过。

问题分析

保存左右两个指针,每轮先移动左指针获得1个字母或数字,其它字符都跳过;然后移动右指针,找到1个字母或数字,其它字符都跳过;如果此时左右两个字符都为字母或数字并但是两个不相等,则返回false;进行下轮指针移动直到两个指针相等。

代码

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.length()==0||s.length()==1) return true;
        int left=0,right=s.length()-1;
        // 大写转小写
        for(int i=0;i<s.length();i++) {
            char ch = s[i];
            if(ch>='A'&&ch<='Z') ch = 'a' + ch - 'A';
            s[i] = ch;
        }
        while(left<right) {
            char l = s[left++];
            char r = s[right--];
            while(!((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&left<s.length()) {
                l = s[left++];
            }
            while(!((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&right>0) {
                r = s[right--];
            }
            if(((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&r!=l) {
                return false;
            }
        }
        return true;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读