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

解析

题目为最长的回文,其意思是根据给定的字符串求其最长的回文串。题目中给定的字符串区分大小写。具体的思路为先扫描字符串,统计大小写字母出现的次数,然后最长的字符串为该统计中偶数字符个数的总和和最大的奇数字符串次数和。
这种思路是错误的!
这是因为奇数的字符串个数 - 1 = 偶数。这个偶数也可以加到结果字符串中。
因此,正确的结果为:
最长的回文 = sum(出现偶数次的字母) + sum(出现奇数次字母 - 1)+ 是否出现奇数次字母?1:0

代码(C语言)

int longestPalindrome(char* s) {
    int len = (int)strlen(s);
    
    if (len == 0)
        return 0;
    
    int* chMapArr = (int*)calloc(58, sizeof(int));
    
    for (int i = 0; i < len; ++i)
        ++chMapArr[s[i] - 'A'];
    
    int result = 0;
    bool isHaveOdd = false;
    
    for (int i = 0; i < 58; ++i) {
        if (i > 25 && i < 32)
            continue;
        
        if (chMapArr[i] % 2 == 0)
            result += chMapArr[i];
        else {
            isHaveOdd = true;
            
            result += (chMapArr[i] - 1);
        }
    }
    
    free(chMapArr);
    
    return result + (isHaveOdd ? 1 : 0);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。