409. Longest Palindrome*
https://leetcode.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.
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.
C++ 实现 1
为了得到最长的回文串, 策略是:
- 统计每个字符的个数
- 如果某个字符个数为
2n
个, 那么就可以全部用来组成回文串 - 如果某个字符的个数为
2n + 1
个, 那么就可以用其中2n
个字符 - 判断已经统计的回文串的长度是否小于输入字符串, 如果是的话, 说明原输入字符串中存在字符个数为奇数的字符, 那么回文串的长度还能再加 1, 因为我们可以把这多出来的字符放在回文串的中间.
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> record;
for (auto &c : s) record[c] ++;
int res = 0;
for (auto &p : record)
res += 2 * (p.second / 2);
res += res < s.size() ? 1 : 0;
return res;
}
};
C++ 实现 2
C++ 实现 1
写麻烦一点的形式, 其中 imax
的结果不是 0 就是 1.
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> record;
for (auto &c : s) record[c] ++;
int res = 0, imax = 0;
for (auto &p : record) {
if (p.second % 2 == 0) res += p.second;
else {
res += 2 * (p.second / 2);
imax = std::max(imax, p.second % 2);
}
}
res += imax;
return res;
}
};
C++ 实现 3
两年前的代码.
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> record;
for (auto &c : s)
record[c] ++;
int len = 0;
for (auto &iter : record) {
if (iter.second >= 2)
len += 2 * (iter.second / 2);
}
if (len < s.size() && (len % 2 == 0))
len += 1;
return len;
}
};