125. Valid Palindrome

欢迎fork and star:Nowcoder-Repository-github

125. Valid Palindrome

题目

  • 注意c/c++大小写的转换方法
  • c基本库函数isalnum(),tolower(),toupper()等基本函数的使用
 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. 

解析

class Solution {
public:
  bool isDigitandApha(char ch)
    {
        if ((ch >= 'a'&&ch <= 'z') || (ch>='0'&&ch<='9'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    bool isPalindrome(string s) {

        int size = s.size();
        int start = 0, end = size - 1;

        
        transform(s.begin(),s.end(),s.begin(),::tolower);
        string copy = s;
        while (start<=end)
        {
            if (isDigitandApha(copy[start])&&isDigitandApha(copy[end]))
            {
                if (copy[start]==copy[end])
                {
                    start++;
                    end--;
                }
                else
                {
                    return false;
                }
            }
            else if (!isDigitandApha(copy[start]))
            {
                start++;
            }
            else if (!isDigitandApha(copy[end]))
            {
                end--;
            }
            else //都不是字符或数字
            {
                start++;
                end--;
            }
        }

        return true;
    }
};

链接:https://www.nowcoder.com/questionTerminal/b4dc0f1ee20448fca1f387fb1546f43f

bool isPalindrome(string s) {
        int i,j;
        for(i=0,j=s.length()-1;i<j;++i,--j){
            while(i<j && !isalnum(s[i])) ++i;
            while(i<j && !isalnum(s[j])) --j;
            if (i<j && tolower(s[i])!=tolower(s[j])) return false;
        }
        return true;
    }
    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8182414.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞