classSolution: defisPalindrome(self, x: int) -> bool: before = x if x < 0: returnFalse res = 0 while x>0: res = res*10 + x%10 x = x//10 return res == before
回文排列(力扣266)
思路:字典判断个数即可,小于等于1个则返回True
1 2 3 4 5 6 7 8 9
from collections import Counter classSolution: defcanPermutePalindrome(self, s: str) -> bool: temp = Counter(s) count = 0 for i in temp: if temp[i]%2 == 1: count += 1 return count <= 1
验证回文串(力扣125)
思路:和上题相同
1 2 3 4
classSolution: defisPalindrome(self, s: str) -> bool: result = "".join(i.lower() for i in s if i.isalnum()) return result == result[::-1]
from collections import Counter classSolution: deflongestPalindrome(self, s: str) -> int: temp = Counter(s) result = 0 flag = False for i in temp: if temp[i]%2 == 0: result += temp[i] else: flag = True result += temp[i] - 1 return result + 1if flag else result
验证回文字符串II(力扣680)
首先想到了暴力法:超出时间限制
1 2 3 4 5 6 7 8 9
classSolution: defisP(self,s): return s == s[::-1] defvalidPalindrome(self, s: str) -> bool: if self.isP(s):returnTrue for index in range(len(s)): if self.isP(s[:index] + s[index+1:]): returnTrue returnFalse