【leetcode】409. 最长回文串(longest-palindrome)(字符串)[简单]

链接

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;
    }
};
发布了76 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Krone_/article/details/104977254
今日推荐