admin管理员组文章数量:1794759
vaild
题目简述
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,不是返回0while(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():将字母变小写。
本文标签: vaild
版权声明:本文标题:vaild 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1692617439a153651.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论