方案一:
一般方法:分奇數偶數來說,方法比較一般
import string
#給join傳遞入參時計算符合條件的字元,去掉標點符號
b =''
.join(c for c in s if c not
in string.punctuation)
#把空格去掉
b=b.replace(
' ','')
#小寫b=b.lower()l=
len(b)
if l ==
0or l ==1:
print
('false'
)else:if
(l%2==0
):for i in
range
(int
(l/2))
:if out[i]
!= out[l-
1-i]
:print
('false'
)else
:for i in
range
(int
(l/2))
:if out[i]
!= out[l-i-1]
:print
('false'
)print
('true'
)方案二:
#字串去掉標點和空格後反轉,反轉前與反轉後相同
import string
b =''
.join(c for c in s if c not
in string.punctuation)
b=b.replace(
' ','')
b=b.lower()l=
len(b)
if l ==
0or l ==1:
print
('false'
)else
:if b==b[::
-1]:
print
('true'
)else
:print
('false'
)方案三:
#使用string的內建函式isalnum()
class
solution
:def
ispalindrome
(self, s)
:"""
:type s: str
:rtype: bool
"""s_new =
list
(filter
(str
.isalnum, s.lower())
)return s_new == s_new[::
-1]方案四:
class
solution
:def
ispalindrome
(self, s)
:"""
:type s: str
:rtype: bool
"""s_new =
[ch for ch in s.lower(
)if ch.isalnum()]
return s_new == s_new[::
-1]方案五:
#使用正則匹配
class
solution
:def
ispalindrome
(self, s)
:"""
:type s: str
:rtype: bool
"""import re
s =''.join(re.findall(r"[0-9a-za-z]"
, s)
).lower(
)return s == s[::
-1]
知識點:
print
(str
.upper())
# 把所有字元中的小寫字母轉換成大寫字母
print
(str
.lower())
# 把所有字元中的大寫字母轉換成小寫字母
print
(str
.capitalize())
# 把第乙個字母轉化為大寫字母,其餘小寫
print
(str
.title())
# 把每個單詞的第乙個字母轉化為大寫,其餘小寫
利用replace(
) 方法去除字串中的空格
replace(
)方法用來替換字串中的指定字串,並可以指定最大替換次數。
語法如下:
str.replace(old, new[
,max])
用這個思路可以用來去除空格:
str=
' this is a string '
print
(str
.replace(
' ','')
)
主要問題是刪除字串中的符號和空格
python filter
() 函式
用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
py3返回的是迭代器元素
語法:filter
(function, iterable)
iterable-
-可迭代元素
function:str
.isdigit-
-只保留數字
str.isalpha-
-只保留字母
str.isalnum-
-保留數字和字母
lambda ch: ch in 『.
..』-
-『..
.』中儲存你想儲存的字元
LeetCode 驗證回文字串
給定乙個非空字串s,最多刪除乙個字元。判斷是否能成為回文字串。示例 1 輸入 aba 輸出 true 示例 2 輸入 abca 輸出 true 解釋 你可以刪除c字元。注意 字串只包含從 a z 的小寫字母。字串的最大長度是50000。思路 雙指標 當不相等的時候 左指標跳過乙個或者右指標跳過乙個 ...
Leetcode 驗證回文字串。
給定乙個字串,驗證它是否是回文串,只考慮字母和數字字元,可以忽略字母的大小寫 說明 本題中,我們將空字串定義為有效的回文串 1.先將字串變為小寫,因為本題忽略了字母的大小寫。2.利用字元的ascii值進行驗證 3.採用雙指標的辦法,乙個指向頭,乙個指向尾,同時向中間靠攏,過程中兩指標指向目標不相等則...
驗證回文字串 leetcode
給定乙個字串,驗證它是否是回文串,只考慮字母和數字字元,可以忽略字母的大小寫。說明 本題中,我們將空字串定義為有效的回文串。示例 1 輸入 a man,a plan,a canal panama 輸出 true 示例 2 輸入 race a car 輸出 false c 版本 class solut...