LeetCode 409. Longest Palindrome 解题 C语言

本文介绍了一种求解给定字符串中能构建的最长回文串长度的方法。通过记录字符出现次数,巧妙处理奇偶数量,实现了简洁高效的算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

看了别人的答案,很多人对回文的定义不太一致。而且很繁琐。

我的solution是 accepted了,所以回文应该和题目是一致的,而且个人觉得比较简单明了。所以就我第一次上传solution分享一下。

思路:用num数组记录各字符出现的次数,偶数的记录回文长度,奇数的先减1再记录长度。设定奇数出现的标志位odd,字符串中有奇数则为1,并使最后的长度+1,否则为0。

该答案刚好考虑了各种特殊情况,也不需要区别对待大小写,大写字母小写字母中间的那些字符出现均为0次,亦不影响结果。

int longestPalindrome(char* s) {

    int i=0,sum=0,odd=0;
    int num[65]={0};C
    for(i=0;s[i]!=NULL;i++)
        num[s[i]-'A']++;
    for(i=0;i<65;i++)
    {
        if(num[i]%2==0)
        sum+=num[i];
        else
        {sum+=num[i]-1;
        odd=1;}
    }
    return sum+odd;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值