Come from : [https://leetcode-cn.com/problems/longest-palindrome/]
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.
Example 1 :
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
Note:
Assume the length of given string will not exceed 1,010.
easy 类型题目。用 字符哈希表。
AC代码如下:
class Solution {
public:
int longestPalindrome(string s) {
int a[128] = {0}; //字符哈希
int sum = 0;
int tag = 0; //判断是否有 中心点 标志位
for(int i = 0; i < s.size(); ++i)
{
++a[s[i]];
}
for(int i = 0; i < 128; ++i)
{
if(a[i] % 2 == 0)
{
sum += a[i];
}
if(a[i] %2 == 1)
{
tag = 1;
sum += a[i] - 1;
}
}
return sum + tag;
}
};
方法:
跟我的做法思路一样。。但是速度排名第一啊~
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char,int>tem;
for(int i=0;i<s.size();i++){
tem[s[i]]++;
}
int flag=0;
int res=0;
for(auto iter=tem.begin();iter!=tem.end();iter++){
int n=iter->second;
if(n%2!=0){
flag++;
res+=n-1;
}else
res+=n;
}
if(flag>0)
res++;
return res;
}
};
感觉还是要系统的掌握知识。。。
比如这次的 哈希表。。。
系统的学习之后,才能更加得心应手的运用~
2019/5/25 胡云层 于南京 86