力扣刷题(第八十五天)
灵感来源
- 保持更新,努力学习
- python脚本学习
最长回文串
解题思路
- 使用哈希表统计每个字符的出现次数。
- 计算所有奇数次数的字符数量。
- 最长回文串长度为原字符串长度减去奇数次数的字符数量加 1(若存在奇数)。
from collections import Counterclass Solution:def longestPalindrome(self, s: str) -> int:# 统计每个字符的出现次数count = Counter(s)odd_count = 0# 计算出现奇数次的字符数量for cnt in count.values():if cnt % 2 != 0:odd_count += 1# 最长回文串长度 = 原长度 - 奇数次数的字符数量 + 1(若存在奇数)return len(s) - odd_count + (1 if odd_count > 0 else 0)
逐行解释
from collections import Counterclass Solution:def longestPalindrome(self, s: str) -> int:# 使用Counter统计每个字符的出现次数# 例如:s = "abccccdd" → count = {'a': 1, 'b': 1, 'c': 4, 'd': 2}count = Counter(s)# 初始化奇数次数的字符数量odd_count = 0# 遍历每个字符的出现次数for cnt in count.values():# 若字符出现次数为奇数,将其计入odd_countif cnt % 2 != 0:odd_count += 1# 计算最长回文串长度:# 1. 原字符串长度减去所有奇数次数的字符各1次(即odd_count)# 2. 若存在奇数次数的字符,可任选一个放在回文串中间,故加1# 例如:s = "abccccdd" → len(s) = 8, odd_count = 2('a'和'b'各出现1次)# 最长回文串长度 = 8 - 2 + 1 = 7(如"dccaccd")return len(s) - odd_count + (1 if odd_count > 0 else 0)