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.
class Solution {
public:
int longestPalindrome(string s) {
vector<int> p(128, 0);
int ans = 0;
int flag = 0;
for(auto c : s)
p[c]++;
for(int i = 0; i < p.size(); i++)
{
if(p[i] == 1)
flag = 1;
if(p[i] >= 2)
{
if(p[i] %2 == 0)
ans += p[i];
else
{
ans += (p[i] -1);
flag = 1;
}
}
}
ans += flag;
return ans;
}
};
better~!!!!!!!
int longestPalindrome(const string &s) {
int count[128]{};
for (auto c : s) ++count[c];
for (auto num : count) count[0] += num & 1;
return s.size() - count[0] + (count[0] > 0);
}
本文介绍了一种高效的算法,用于从给定字符串中构建最长的回文子串。通过对字符出现次数的统计,该算法能巧妙地处理奇偶数量的字符,以确保所构建的回文子串长度最大化。
386

被折叠的 条评论
为什么被折叠?



