Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
Solution: Two pointers
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Solution { public: bool isPalindrome(string s) { int i = 0; int j = s.length() - 1; while (i < j) { while (i < j && !isalnum(s[i])) ++i; while (i < j && !isalnum(s[j])) --j; if (tolower(s[i++]) != tolower(s[j--])) return false; } return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment