[LeetCode]40. Valid Palinadrome有效回文串
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:先扫描一遍字符串,将除数字和字母外的字符扔掉,并且都转为小写;然后两个指针从两头向中间靠拢,一一比较对应字符是否相同即可。
class Solution { public: bool isPalindrome(string s) { int i = 0, k = 0; for (; i < s.size(); i++) { if ((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) s[k++] = (char)tolower(s[i]); } int left = 0, right = k - 1; while (left <= right) { if (s[left] != s[right]) return false; ++left; --right; } return true; } };
解法2:第二个方法是两个指针从两头向中间靠拢,如果碰到非数字字母字符则跳过,然后一一比较即可。
class Solution { public: bool isPalindrome(string s) { int n = s.size(); int i = 0, j = n - 1; while (i <= j) { while (i < n && !isAlphanumeric(s[i])) ++i; while ( j >= 0 && !isAlphanumeric(s[j])) --j; if (i < n && j >= 0 && tolower(s[i]) != tolower(s[j])) return false; ++i; --j; } return true; } private: bool isAlphanumeric(const char c) { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) return true; return false; } };