链接
https://leetcode-cn.com/problems/longest-palindrome/
耗时
解题:30 min
题解:7 min
题意
给定一个只包含大小写字母的字符串,使用字符串中的字符构造最长的回文串,返回最长的回文串的长度。(字符串的长度
≤
\leq
≤ 1010)
思路
使用哈希表记录字符串中每个字母的数量。然后遍历哈希表,若字母的数量是奇数,则将数量减一加入答案,若字母的数量是偶数,则直接加入答案,最后若存在字母的数量是奇数,则答案加一。
AC代码
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> hmap;
for(char c:s) {
hmap[c]++;
}
int ans = 0;
bool flag = false;
for(unordered_map<char, int>::iterator it = hmap.begin(); it!=hmap.end(); ++it) {
if((it->second)&1) {
ans += (it->second)-1;
flag = true;
}
else ans += (it->second);
}
if(flag) ans+=1;
return ans;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)