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多
c版本 4ms,比c++效率高,直接使用指针的效率更高
*
* 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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解