409. Longest Palindrome(python+cpp)
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83183329
题目:
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note: Assume the length of given string will not exceed 1,010.
Example:Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd",whose length is 7.
解释:
主要考虑字母在字符串中出现的次数是奇数次还是偶数次。
python代码:
from collections import Counter
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
result=0
have_odd=False
_dict=Counter(s)
for key in _dict:
if _dict[key]%2==0:
result+=_dict[key]
else:
result+=_dict[key]-1
have_odd=True
return result+1 if have_odd else result
c++代码:
class Solution {
public:
int longestPalindrome(string s) {
map<char,int> count_map;
for(auto letter:s)
count_map[letter]+=1;
int result=0;
bool have_odd=false;
for(auto &item:count_map)
{
if(item.second%2==0)
result+=item.second;
else
{
result+=item.second-1;
have_odd=true;
}
}
return have_odd?result+1:result;
}
};
总结:
相比之下,字典真的是太省时间了。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。