vaild-palindrome

版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/82669252

题目简述

  • 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.

  • 给定一个字符串,确定它是否是回文,只考虑字母数字字符并忽略大小写。例如, “A man, a plan, a canal: Panama”是一个回文。”race a car”不是回文。注意: 你认为字符串可能是空的吗? 在面试中这是一个很好的问题。出于此问题的目的,我们将空字符串定义为有效回文。

  • 非递归方法:指针1从前往后遍历,指针2从后往前遍历,遇到非字母数字的字符跳过,比较前后对应字母数字是否相等。

class Solution {
public:
    bool isPalindrome(string s) {
        int lens=s.length();
        for(int i=0,j=lens-1;i<j;++i,--j){
            //跳过前面无用字母
            //两个函数:
            //isalnum()函数:是数字和字母返回1,不是返回0
            //isalpha()函数:是字母返回1,不是返回0
            while(i<j && !isalnum(s[i])){
                ++i;
            }
            //跳过后面无用字母
            while(i<j && !isalnum(s[j])){
                --j;
            }
            //比较是否相等:tolower()将字母变小写
            if(i<j && tolower(s[i])!=tolower(s[j]))
                return false;
        }
        return true;
    }
};
  • 注意

  • isalnum()函数:是数字和字母返回1,不是返回0。

  • isalpha()函数:是字母返回1,不是返回0。

  • tolower():将字母变小写。

猜你喜欢

转载自blog.csdn.net/weixin_40087851/article/details/82669252
今日推荐