首页 > 代码库 > 409. Longest Palindrome

409. Longest Palindrome

 感觉需要注意的点就是在A-Z和a-z之间还夹了6个其他的字符,所以统计的时候不能用new int[52]需要new int[58]

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     public int longestPalindrome(String s) {
 2         if(s == null) {
 3             return 0;
 4         }
 5         int[] count = new int[60];
 6         for(int i = 0; i < s.length(); i++) {
 7             count[s.charAt(i) - ‘A‘]++;
 8         }
 9         boolean hasOdd = false;
10         int res = 0;
11         for(int i = 0; i < 60; i++) {
12             if(count[i] % 2 == 0) {
13                 res += count[i];
14             } else {
15                 res += count[i] - 1;
16                 hasOdd = true;
17             }
18         }
19         res += hasOdd? 1: 0;
20         return res;
21     }

 

409. Longest Palindrome