您的位置:首页 > 其它

【初级算法】16. 验证回文字符串

2018-05-03 13:21 274 查看

题目:

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:

输入: "race a car"
输出: false

1.解题思路:

本题比较简单,直接取字符串的前后字母进行比对,如果相等则前进,否则返回错误。

 

class Solution {
public:
bool isPalindrome(string s) {
int len = s.size();
int start = 0;
int end = len-1;

while(start < end){
char first,second;
/*get the fisrt char*/
while(start <= end){
if((s[start] >= 'a' && s[start] <= 'z')||
(s[start] >= 'A' && s[start] <= 'Z')||
(s[start] >= '0' && s[start] <= '9')){
first = s[start];
if(s[start] >= 'A' && s[start] <= 'Z'){
first = first-'A'+'a';
}
break;
}else{
start++;
}
}

/*get the second char*/
while(start <= end){
if((s[end] >= 'a' && s[end] <= 'z')||
(s[end] >= 'A' && s[end] <= 'Z')||
(s[end] >= '0' && s[end] <= '9')){
second = s[end];
if(second <= 'Z'&&second>='A'){
second = second-'A'+'a';
}
break;
}else{
end--;
}
}

if(start > end){
break;
}

if(first == second){
start++;
end--;
}else{
return false;
}
}

return true;
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: