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.

 

要完成的函数:

int longestPalindrome(string s) 

说明:

1、这道题给定一个字符串,要求用字符串中的元素(包含大写字母和小写字母)组成一个尽可能长的回文串,最后返回这个回文串的长度。

比如字符串为"abccccdd",那么我们有两个d,四个c,一个b,一个a,所以我们可以组成一个最长的回文串是“dccaccd”,长度为7。

注意"Aa"在这道题目中,不被认为是回文串,也就是大小写敏感。

2、所以这道题我们统计一下有多少个偶数个数的字母,用长度为26*2=52的vector存储字母的出现次数。

出现一对偶数个数的字母的时候,结果+2。

最后再看一下有没有单个的字母,如果有,就加1,如果没有,那么结果不改变。

代码如下:(附详解)

    int longestPalindrome(string s) 
    {
        vector<int>lettercount(52,0);//存放26个小写字母和26个大写字母
        int result=0,t1,t2;//t1和t2是临时变量
        for(char a:s)//我发现这种写法比传统的int i=0;i<s.size();i++方便很多
        {
            if(islower(a))//大小写分开处理
            {
                t1=a-'a';
                if(lettercount[t1]==1)//如果之前已经出现过了
                {
                    result+=2;
                    lettercount[t1]=0;
                }
                else//如果之前没有出现过
                    lettercount[t1]=1;
            }
            else//大小写分开处理
            {
                t2=a-'A'+26;
                if(lettercount[t2]==1)
                {
                    result+=2;
                    lettercount[t2]=0;
                }
                else
                    lettercount[t2]=1;
            }
        }
        for(int i:lettercount)//最后遍历一遍52个元素,看有没有单个的元素
        {
            if(i==1)
            {
                result++;
                break;
            }
        }
        return result;
    }

上述代码实测6ms,beats 98.02% of cpp submissions。

原文地址:https://www.cnblogs.com/chenjx85/p/9151894.html