Valid Palindrome

描述

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.

分析

代码

  1. // Valid Palindrome
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. bool isPalindrome(string s) {
  6. transform(s.begin(), s.end(), s.begin(), ::tolower);
  7. auto left = s.begin(), right = prev(s.end());
  8. while (left < right) {
  9. if (!::isalnum(*left)) ++left;
  10. else if (!::isalnum(*right)) --right;
  11. else if (*left != *right) return false;
  12. else { left++, right--; }
  13. }
  14. return true;
  15. }
  16. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/string/valid-palindrome.html