您的位置:首页 > 编程语言 > C语言/C++

Valid Palindrome

2016-07-14 20:36 429 查看
一、问题描述

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.

Subscribe to see which companies asked this question

二、思路

版本一:暴力求解。将数字和字符串存储在另一个字符串中,将大写字母全部变为小写字母,判断是否是回文串。超时

版本二:采用两个库函数,isalnum()函数识别是否是子母和数字;tolower()将所有的大写字母变为小写字母,其余字符不做处理。

三、代码

版本一:超时不通过

class Solution {
public:
bool isPalindrome(string s) {
string t = "";
if(s == "") return true;
for(int i = 0; i < s.size(); ++i)
if(s[i] >= 65 && s[i] <= 90 || s[i] >= 97 && s[i] <= 122 || s[i] >= 48 && s[i] <= 57)
t = t + s[i];
for(int l = 0; l < t.size(); ++l)
if(t[l] >= 65 && t[l] <= 90)
t[l] += 32;
for(int j = 0,k = t.size() - 1; j < k; ++j,--k)
if(t[j] != t[k])
return false;
return true;
}
};


版本二

class Solution {
public:
bool isPalindrome(string s) {
int i = 0,j = s.size() - 1;
while(i < j){
while(!isalnum(s[i]) && i < j) i++;
while(!isalnum(s[j]) && i < j) j--;
if(tolower(s[i++]) != tolower(s[j--]))
return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++