LeetCode 409. Longest Palindrome (算法、回文序列)

来源:互联网 发布:js里面遍历树形json 编辑:程序博客网 时间:2024/06/03 16:00

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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.
输入一组字母(区分大小写),判断由其子集组成的回文序列最大长度。

思路

回文序列的构成:偶数个A+偶数个B+任意个C+偶数个B+偶数个A。若C、D、E的个数是奇数,想使得序列最长,则需要将最长的奇数个字母放在中间,其他字母数量减一变成偶数个字母放在两边。

当不存在奇数个字母时,长度=sum(偶数);当存在奇数个字母时,长度=sum(偶数)+sum(奇数-1)+1。

    int longestPalindrome(string s) {        int count[52],i,even=0,odd=0,oddflag=0;        for(i=0;i<52;i++)count[i]=0;        for(i=0;i<s.size();i++)        {            if(s[i]<=90) //uppercase                count[s[i]-'A']++;            else //lowercase                count[s[i]-'a'+26]++;        }        for(i=0;i<52;i++)        {            if(count[i]%2==0)even+=count[i];            else             {                odd+=count[i]-1;                oddflag = 1;            }        }        return oddflag>0?even+odd+1:even;    }




原创粉丝点击