leetcode——Valid Palindrome
这题算是简单,但是还是有错到我都不知道为啥错要启动编译器来调试的时候,原来是不知道有个判断字母的函数是isalnum(),于是自己写了个判断字母的函数,第一次没判断数字,就错了,第二次发现发现判断字母时我是判断A~z则是字母,但是A和a之间隔了32个字符,而大写字母只有26个,说明之间还有不是字母的字符也被我判断进去了。。。。怪不得以前看别人的程序判断字母时都是判断A~Z || a~z,原来细节问题我没有注意到。
在看了别人的答案我又查了查,可以多积累三个函数:
1. isalnum(): 判断是否是字母和数字
2. isalpha(): 判断是否是字母
3. isdigit(): 判断是否是数字
下面是用我自己写的判断字母函数的代码:
class Solution {
public:
// 有一个指向头和一个指向尾的指针,如果是字符则比对,或+32或-32比对,若不相同则返回false,若相同则继续,知道头尾指针相遇返回true
bool isPalindrome(string s) {
int head(0), tail(s.size() - 1);
char headChar, tailChar;
while (head < tail){
while (head < tail && !isAlphanumeric(s[head]))
head++; // 不是字母或数字
while (head < tail && !isAlphanumeric(s[tail])) tail--;
headChar = s[head];
tailChar = s[tail];
if (headChar != tailChar && (headChar + 32) != tailChar && (headChar - 32) != tailChar) return false;
head++;
tail--;
}
return true;
}
inline bool isAlphanumeric(char c){
if ((c >= 'A' && c <= 'Z') || ( c >= 'a' && c <= 'z'))
return true;
if (c >= '0' && c <= '9')
return true;
return false;
}
};
下面是换了isalnum()函数的,确实简洁多了,而且很神奇的,速度貌似也快上了一点
class Solution {
public:
// 有一个指向头和一个指向尾的指针,如果是字符则比对,或+32或-32比对,若不相同则返回false,若相同则继续,知道头尾指针相遇返回true
bool isPalindrome(string s) {
int head(0), tail(s.size() - 1);
char headChar, tailChar;
while (head < tail){
while (head < tail && !isalnum(s[head]))
head++; // 不是字母或数字
while (head < tail && !isalnum(s[tail])) tail--;
headChar = s[head];
tailChar = s[tail];
if (headChar != tailChar && (headChar + 32) != tailChar && (headChar - 32) != tailChar) return false;
head++;
tail--;
}
return true;
}

浙公网安备 33010602011771号