您的位置:首页 > 其它

LeetCode 125. Valid Palindrome

2016-06-30 15:43 447 查看
/[b]************************************************************************[/b]

*

* 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.

*

*

[b]************************************************************************[/b]/

c++版本 12ms,分析应该是因为重载的s[]操作耗时比c多

bool isPalindrome(string s) {
int i = 0, j = s.size() - 1;
while(i < j) {
while(i < j && !isalnum(s[i])) i++;
while(i < j && !isalnum(s[j])) j--;
if (toupper(s[i])!=toupper(s[j]))
return false;
i++;j--;
}
return true;
}


c版本 4ms,比c++效率高,直接使用指针的效率更高

bool isPalindrome(char* s) {
char *p1 = s, *p2 = s + strlen(s) - 1;
while(p1 < p2){
if(!isalnum(*p1)){p1++;continue;}
if(!isalnum(*p2)){p2--;continue;}
if(tolower(*p1++) != tolower(*p2--)) return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode