您的位置:首页 > 其它

leetcode | Valid Palindrome

2015-06-21 16:44 375 查看
Valid Palindrome : https://leetcode.com/problems/valid-palindrome/

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.

解析

alphanumeric characters :字母或数字型字符

本题难点在于:

1. 全空格字符串应判断为true

2. 字母不区分大小写

一种算法就是,将原字符串剔除所有非字母数字字符,插入到一个新的字符串空间,然后基于新字符串,用2个指针法做判断。算法实现简单,不需额外考虑全空格字符串,但是占用额外空间。

另一种算法是,用2个指针指向字符串两头,当遇到非字母数字字符时跳过,然后做处理。对于全空格字符串,通过判断左指针是否会到达字符串尾部。,优点是不占用额外空间,时间复杂度上也优于第一种(只需遍历一次数组)。

算法 1 实现

class Solution {
public:
bool isPalindrome(string s) {
string s2;
int i = -1;
while (++i < s.size()) {
if ((s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9'))
continue;
else
s2 += s[i];
}
i = -1;
int j = s2.size();
if (j == 0)
return true;
int interval = 'a' - 'A';
while (++i <= --j) {
if (!(s2[i] == s2[j] || s2[i]+interval == s2[j] || s2[i]-interval == s2[j]))
return false;
}
return true;
}
};


算法 2 实现

class Solution {
public:
bool isPalindrome(string s) {
if (s.size() == 0)
return true;
int i = -1;
int j = s.size();
int interval = 'a' - 'A';
while (++i <= --j) {
while ((i < j) && (s[i] < 'A' || s[i] > 'Z') && (s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9'))
i++;
while ((i < j) && (s[j] < 'A' || s[j] > 'Z') && (s[j] < 'a' || s[j] > 'z') && (s[j] < '0' || s[j] > '9'))
j--;
// 全空格字符串
if (i == s.size()-1)
return true;
if (s[i] != s[j] && s[i]+interval != s[j] && s[i]-interval != s[j])
return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: