题目链接:https://leetcode.com/contest/7/problems/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.
思路:
easy 统计每种字符出现次数,分奇偶情况讨论。
算法:
public int longestPalindrome(String s) {
if (s.length() == 0)
return 0;
int lm[] = new int[26];
int um[] = new int[26];
for (char c : s.toCharArray()) {
if (Character.isLowerCase(c))
lm[c - 'a']++;
else
um[c - 'A']++;
}
int count = 0;
boolean flag = false;// 是否有单个字符
for (int num : lm) {
if (num % 2 == 0) {
count += num;
} else {
if (flag) {
count += num - 1;
} else {
count += num;
flag = true;
}
}
}
for (int num : um) {
if (num % 2 == 0) {
count += num;
} else {
if (flag) {
count += num - 1;
} else {
count += num;
flag = true;
}
}
}
return count;
}