LeetCode刷题笔记 409. 最长回文串 【哈希表】【数组保存】

哈希表

最长回文串

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> count;
        int ans = 0;
        for (char c : s)
            ++count[c];
        for (auto p : count) {
            int v = p.second;
            ans += v / 2 * 2;
            / 发现了第一个出现次数为奇数的字符后,我们将 ans 增加 1,这样 ans 变为奇数,
            / 在后面发现其它出现奇数次的字符时,我们就不改变 ans 的值了。
            if (v % 2 == 1 and ans % 2 == 0)
                ++ans;
        }
        return ans;
    }
};

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char,int> count;
        for(char ch:s)count[ch]++;
        int res=0;
        for(auto it:count){
            if(it.second&1)res+=it.second-1; / 加上奇数字符数-1
            else res+=it.second; / 加上偶数字符数
        }
        return res<s.size()?res+1:res; / 加上一个单字符放在中间
    }
};

数组保存

图解回文串 C++

在这道题上优势不大

class Solution {
public:
    int longestPalindrome(string s) {
        int hashCount[52] = {0};
        for(int i = 0; i < s.size(); i++) {
            if('a' <= s[i] && s[i] <= 'z') {
                hashCount[s[i]-'a']++;
            } else {
                hashCount[s[i]-'A'+26]++;
            }
        }
        int sum = 0;
        for(int i = 0; i < 52; i++) {
            if((sum&1) && (hashCount[i]&1)) {
                sum += hashCount[i]-1;
            } else {
                sum += hashCount[i];
            }
        }
        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值