1. 題目
https://leetcode-cn.com/problems/longest-palindrome/
給定一個(gè)包含大寫字母和小寫字母的字符串,找到通過(guò)這些字母構(gòu)造成的最長(zhǎng)的回文串。
在構(gòu)造過(guò)程中,請(qǐng)注意區(qū)分大小寫。比如 "Aa" 不能當(dāng)做一個(gè)回文字符串。
注意:
假設(shè)字符串的長(zhǎng)度不會(huì)超過(guò) 1010。
示例 1:
輸入:
"abccccdd"
輸出:
7
解釋:
我們可以構(gòu)造的最長(zhǎng)的回文串是"dccaccd", 它的長(zhǎng)度是 7。
2. 我的AC
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
mapping = {}
for char in s:
if char not in mapping:
mapping[char] = 1
else:
mapping[char] += 1
count_odd = 0
for _, num in enumerate(mapping.values()):
if num % 2 == 1:
count_odd += 1
return len(s) - count_odd + 1if count_odd > 0 else len(s)
出錯(cuò)點(diǎn)注意:
-
aaa可以只取aa
3. 小結(jié)
- 遍歷列表元素
- 效率較低
for num in list:
- 效率較高
for _, num in enumerate(list):