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.
Subscribe to see which companies asked this question.
编程中要注意是,如果有单个的最后要加上1,因为可以放在中间。
public class Solution {
public int longestPalindrome(String s) {
int len = 0;
int[] a = new int[52];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) <= 'Z') {
a[s.charAt(i) - 'A']++;
} else {
a[s.charAt(i) - 'a' + 26]++;
}
}
for (int j = 0; j < a.length; j++) {
if (a[j] != 0) {
if (a[j] % 2 == 0) {
len += a[j];
} else {
if (len % 2 == 0) {
len += a[j];
} else {
len = len + a[j] - 1;
}
}
}
}
return len;
}
}