LeetCode 125. Valid Palindrome
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
method: 双指针
isalnum()判断字符是不是字母或数字isalpha()判断是不是字母isdigit()判断是不是数字isspace()判断是不是空格tolower()转化为小写字母toupper()转化为大写字母
分别从两边找符合条件的字母或数字
// 判断是不是字母或数字,可以用isalnum()代替
bool isValue(char c) {
if (isdigit(c) || isalpha(c))
return true;
return false;
}
bool isPalindrome(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
while (i < j && !isValue(s[i])) i++;
while (i < j && !isValue(s[j])) j--;
if (tolower(s[i]) != tolower(s[j])) return false;
++i;
--j;
}
return true;
}
LeetCode 680. Valid Palindrome II
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
method: 双指针
遇到不相等的地方,就考虑删掉一个的情况,如果删掉还不行,那就不行了
可以删掉i后面的,或者j前面的
bool isPalindrome(string s, int i, int j) {
while (i < j) {
if (s[i] != s[j]) return false;
i++;
j--;
}
return true;
}
bool validPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; ++i, --j) {
if (s[i] != s[j]) {
return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
// 删掉i后面的或j前面的
}
}
return true;
}