409. Longest Palindrome
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome here.
Example 1:
Input: s = “abccccdd”
Output: 7
Explanation: One longest palindrome that can be built is “dccaccd”, whose length is 7.
Example 2:
Input: s = “a”
Output: 1
Explanation: The longest palindrome that can be built is “a”, whose length is 1.
Constraints:
1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.
solution1贪心、奇偶性
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> count;
int ans = 0;
for (char c : s)
++count[c];
for (auto p : count) {
int v = p.second;
ans += v / 2 * 2;
if (v % 2 == 1 and ans % 2 == 0)
++ans;
}
return ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/longest-palindrome/solution/zui-chang-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1.用哈希表统计每个字符出现的次数
2.判断奇偶性:
若字符出现次数为偶数,则肯定能够组成回文串,计入累加器
若为奇数,添加个数-1并计入累加器,并且标记存在中心字符
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> hash;
for (auto x : s) hash[x] ++;
int res = 0, center = 0;
for (auto item : hash){
if (item.second % 2 == 0)
res += item.second;
else{
res += item.second - 1;
center = 1;
}
}
return res + center;
}
};
作者:wangtao27
链接:https://leetcode.cn/problems/longest-palindrome/solution/li-yong-ha-xi-biao-yu-qi-ou-xing-ben-ti-ke-jie-by-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
vector<int> m(128,0);
int len=0;
for(auto c:s) {
if(m[c]&1) len+=2;
m[c]++;
}
if(len<s.size()) len++;
return len;