您的位置:首页 > 其它

Leetcode 125 Valid Palindrome

2017-07-01 15:56 369 查看

Leetcode 125 Valid Palindrome

#include <string>
#include <algorithm>
using namespace std;

class Solution {
public:
bool isPalindrome(string s) {
if (s.empty())
return true;
for (int i = 0;i < s.size();i ++){
if (!isalpha(s[i]) && !isdigit(s[i])){
s.erase(i, 1);
i--;
}
}
transform(s.begin(), s.end(), s.begin(), ::tolower);
string newstr = s;
reverse(s.begin(), s.end());
if (newstr == s)
return true;
else
return false;
}
};//龟速的代码,不应该这么写

class Solution {
public:
bool isPalindrome(string s) {
//if (s.empty())
//  return true;
int begin = 0;
int end = s.size() - 1;//两头两个指针移动
while (begin < end){
if (!isalnum(s[begin]))
begin++;//找到开头开始比的地方
else if (!isalnum(s[end]))
end--;//找到开头之后要找个结尾
else if ((s[begin] + 32 - 'a') % 32 != (s[end] + 32 - 'a') % 32)//找好开头和结尾之后就要进行比较
return false;
else{
begin++;
end--;
}
}
return true;
}
};//使用isalnum会比自己写慢么?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode