一、125. 验证回文串
1.1、题目描述
class Solution:
def isPalindrome(self, s: str) -> bool:
l = 0
r = len(s)-1
while l bool:
'''
解法1 中心扩散法
首先要先剔除掉非数字字母部分
然后找到字符串的中心,由于中心位置因为字符串长度是奇数还是偶数而不同,所以构造字符串,弄成奇数,长度除以2就是中心位置,
从中心点左右扩散比较是否一样,如果不一样就跳出
'''
ss = ''
for c in s:
if c.isalnum():
ss += c
lens = len(ss)
mid = lens>>1
for i in range(mid):
if ss[i].upper() != ss[lens - 1 - i].upper():
return False
return True
二、9. 回文数
2.1、题目描述
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
2.2.1、第一种解法class Solution:
def isPalindrome(self, x: int) -> bool:
if x tmp:
tmp = tmp * 10 + x % 10
x = x // 10
return x == tmp or x == tmp // 10
三、234. 回文链表
3.1、题目描述
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
s = []
while head:
s.append(head.val)
head = head.next
return self.isPalindromeStr(s)
def isPalindromeStr(self, s: List[int]) -> bool:
l = 0
r = len(s)-1
while l int:
cset = {}
for c in s:
if c in cset:
cset[c] += 1
else:
cset[c] = 1
count = 0 # 单个字母的次数
hasOne = True
for v in cset.values():
count += v // 2 * 2
# 对于奇数个相同字符的字符串
if v % 2 == 1 and count %2 == 0:
count += 1
return count