Leetcode刷题86-409. 最长回文串(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/longest-palindrome/]

1.Question

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.

Example 1 :

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

Note:

Assume the length of given string will not exceed 1,010.

2.Answer

easy 类型题目。用 字符哈希表。

AC代码如下:

class Solution {
public:
    int longestPalindrome(string s) {
        int a[128] = {0}; //字符哈希
        int sum = 0;
        int tag = 0;   //判断是否有 中心点 标志位
        for(int i = 0; i < s.size(); ++i)
        {
            ++a[s[i]];
        }
        for(int i = 0; i < 128; ++i)
        {
            if(a[i] % 2 == 0)
            {
                sum += a[i];
            }
            if(a[i] %2 == 1)
            {
                tag = 1;
                sum += a[i] - 1;
            }
        }
        return sum + tag;
    }
};

3.大神们的解决方案

方法:
跟我的做法思路一样。。但是速度排名第一啊~

class Solution {
public:
    int longestPalindrome(string s) {
        
        unordered_map<char,int>tem;
        for(int i=0;i<s.size();i++){
            tem[s[i]]++;
        }
        int flag=0;
        int res=0;
        for(auto iter=tem.begin();iter!=tem.end();iter++){
            int n=iter->second;
            if(n%2!=0){
                flag++;
                res+=n-1;
            }else
                res+=n;
        }
        if(flag>0)
            res++;
        return res;
    }
};

4.我的收获

感觉还是要系统的掌握知识。。。
比如这次的 哈希表。。。
系统的学习之后,才能更加得心应手的运用~

2019/5/25 胡云层 于南京 86

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值