125. Valid Palindrome(python+cpp)
阿新 • • 發佈:2018-12-19
題目:
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
解釋:
判斷一個句子是不是迴文,去掉標點符號,把句子轉換成小寫。
不要用replace()
了,因為特殊符號了,判斷這個字元是不是alphanumeric然後小寫化後加入到一個新的字串中。
python程式碼:
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s= [x for x in s.lower() if x.isalnum()]
return s==s[:: -1]
c++程式碼:
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(),s.end(),s.begin(),::tolower);
string new_s="";
for (auto letter:s)
{
if (isalnum(letter))
new_s+=letter;
}
string reverse_new_s(new_s);
reverse(reverse_new_s.begin(),reverse_new_s.end());
return new_s==reverse_new_s;
}
};
總結:
<cctype>
裡面:
大小寫轉換:
transform(s.begin(),s.end(),s.begin(),::tolower)
判斷是不是字元數字的:
isalnum(c)