題目:
給定一個包含大寫字母和小寫字母的字符串,找到通過這些字母構造成的最長的迴文串。
在構造過程中,請注意區分大小寫。比如 "Aa"
不能當做一個迴文字符串。
注意:
假設字符串的長度不會超過 1010。
示例 1:
輸入: "abccccdd" 輸出: 7 解釋: 我們可以構造的最長的迴文串是"dccaccd", 它的長度是 7。
python代碼1:
class Solution(object):
def longestPalindrome(self, s):
for i in s:
if i in char_dict:
char_dict[i] += 1
else:
char_dict[i] = 1
for i in char_dict:
if char_dict[i] % 2 == 0:
sum += char_dict[i]
elif char_dict[i] % 2 == 1:
sum += char_dict[i]-1
single = 1
return sum + single
python代碼2:
class Solution:
def longestPalindrome(self, s):
res = 0
for n in collections.Counter(s).values():
res += n - int(n % 2)
return res + int(res < len(s))
心得:哈希錶速度確實快一些。