###### tags: `Leetcode` `easy` `pointer` `python` `c++` # 125. Valid Palindrome ## [題目來源:] https://leetcode.com/problems/valid-palindrome/ ## 題目: A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise. ## 解題想法: 因為有空格 可直接用.isalnum()來判斷是否為字母 head、tail指向s頭尾 依序比較是否相等 ## Python: ``` python= class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ head=0 tail=len(s)-1 while head<tail: #isalnum():字母或數字為true while head<tail and not s[head].isalnum(): #非字母 head+=1 while head<tail and not s[tail].isalnum(): tail-=1 if head<tail: if s[head].lower()!=s[tail].lower(): return False head+=1 tail-=1 return True result = Solution() s = "Abb" #s = "A man, a plan, a canal: Panama" ans = result.isPalindrome(s) print(ans) ``` ## C++ ``` cpp= #include<iostream> #include<cctype> using namespace std; class Solution { public: bool isPalindrome(string s) { int head=0; int tail=s.size()-1; while (head<tail){ while (head<tail && !isalnum(s[head])){ head+=1; } while (head<tail && !isalnum(s[tail])){ tail-=1; } if (head<tail){ //tolower: turn to lower if (tolower(s[head])!=tolower(s[tail])) return false; head+=1; tail-=1; } } return true; } }; int main(){ Solution res; string s="AbAc"; bool ans=res.isPalindrome(s); cout<<ans<<endl; return 0; } ```