[leetcode]125. Valid Palindrome
阿新 • • 發佈:2018-12-04
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
分析:
驗證是否為迴文字串,只考慮字母和數字,忽略大小寫。可以用雙指標分別從頭和尾依次遍歷,遇到非字母數字字元則跳過,否則比較是否相等,出現不一樣的就返回false,若兩指標相遇仍相等則為true。其中需要注意的是不區分字母的大小寫,由於小寫字母的ACSCII碼值比大寫字母大32,所以%32求餘數,餘數相等則認為是相同字元。
class Solution { public: bool isPalindrome(string s) { int left = 0; int right = s.size()-1; while(left < right) { if(!isalphanum(s[left])) left++; else if(!isalphanum(s[right])) right--; else if((s[left]+32-'a')%32 != (s[right]+32-'a')%32) { return false; } else { left++; right--; } } return true; } bool isalphanum(char &c) { if(c>='a' && c<='z') return true; if(c>='A' && c<='Z') return true; if(c>='0' && c<='9') return true; else return false; } };