409. Longest Palindrome*

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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值