Leetcode No.125 Valid Palindrome(c++实现)
作者:互联网
1. 题目
1.1 英文题目
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
1.2 中文题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
1.3输入输出
输入 | 输出 |
---|---|
s = "A man, a plan, a canal: Panama" | true |
s = "race a car" | false |
1.4 约束条件
- 1 <= s.length <= 2 * 105
- s consists only of printable ASCII characters.
2. 分析
2.1 一般算法
简单粗暴,样例通过,但是测试超时
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
while (s[i] < 65 || (s[i] > 90 && s[i] < 97) || s[i] > 122) {
++i;
}
while (s[j] < 65 || (s[j] > 90 && s[j] < 97) || s[j] > 122) {
--j;
}
int temp = s[i] - s[j];
if (temp != 32 && temp != -32 && temp != 0) {
return false;
}
++i;
--j;
}
return true;
}
};
2.2 大神算法
参考:https://leetcode.com/problems/valid-palindrome/discuss/40048/Here's-a-clean-C%2B%2B-solution
class Solution {
public:
bool isPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric
while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric
if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
}
return true;
}
};
注意:isalnum的用法:https://www.cplusplus.com/reference/cctype/isalnum/
标签:Palindrome,return,isalnum,--,c++,while,Valid,&&,false 来源: https://www.cnblogs.com/yunmeng-shi/p/15084994.html