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. 解题思路

我们发现结果其实就是字符的偶数个数+是否有单一的字符,如果有就加1(把单一字符放在回文中间),如果没有就加0;
字母区分大小写,int[] map=new int['z'-'A'+1];
2.代码

public class Solution {
    public int longestPalindrome(String s) {
        if(s.length()==0||s==null) return 0;
        int[] map=new int['z'-'A'+1];
        int count=0;
        int hasOdd=0;
        for(int i=0;i<s.length();i++){
            map[s.charAt(i)-'A']++;
        }
        for(char c='A';c<='z';c++){
            if((map[c-'A'] & 1)==1){
                hasOdd=1;
                count+=(map[c-'A']-1);
            }
            else 
                count+=map[c-'A'];
        }
        return count+hasOdd;
    }
}

tiffanytown
6 声望2 粉丝

keep learning