409. 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.

题解

问一个字符串能排出的回文串的最大长度。

这题考察回文串的性质,x(a)y是回文串的基本形式,其中a为可有可无的单一字符,x为任意多个字符,y与x对称。所以,除了a以外所有字符都可配对,可以判断原字符串各字符出现次数得解。

下面是我的初始代码,通过unorded_map记录原字符串每个字符的出现次数。遍历,如果出现次数是奇数,就将odd赋为1,说明中间的单一字符a是存在的,之后无论奇偶都取偶数部分,加入sum。遍历完sum加上odd,返回。

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char,int> haha;
        //统计次数
        for(int i = 0; i < s.length(); i++){
            if(haha.find(s[i]) == haha.end()){
                haha[s[i]] = 1;
            }else{
                haha[s[i]]++;
            }
        }
        //遍历
        unordered_map<char,int>::iterator itr;
        int odd = 0, sum = 0;
        for(itr = haha.begin(); itr != haha.end(); itr++){
            if(itr->second % 2) odd = 1; //中间的单一字符是否存在
            sum += itr->second / 2 * 2; //偶数部分
        }
        sum += odd;
        return sum;
    }
};

上面写的较麻烦,能不能写的简单点,可不可以不用遍历map?
再次思考,原字符串所有可以配对的字符都可以分别放入x和y,如果配对后还有单一字符就挑一个放入a。那我可以每配对一次就消除这两个字符并计数count+2,同时考虑极端情况,所有字符都可配对,则最后count等于原字符串长度,否则说明必然有单一字符,count+1.
代码如下

class Solution {
public:
    int longestPalindrome(string s) {
        vector<int> haha(256, 0);    
        int count = 0;
        for(int i = 0; i < s.length(); i++){
            //已经有了该字符,配对成功
            if(haha[s[i]])  count += 2;
            //已经有了就消除(0),没有就标记(1)
            haha[s[i]] = 1 - haha[s[i]];
        }
        return count == s.length() ? count : count + 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值