题目:
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.利用数组map[256]将每个字符出现的次数保存起来;
2.用计数器count作为计数变量,再遍历一次字符数组,看字符串中是否出现次数为奇数的元素,如果出现,置count=1;
3.遍历map数组,如果map[i]为偶数,则说明可以作为最长回文串的一部分,如果map[i]为奇数,那么map[i]-1也可以作为最长回文串的一部分;
4.最后返回count即可。
代码:
public class Solution {
public int longestPalindrome(String s) {
if (s.length() == 0) {
return 0;
}
int[] map = new int[256];
for(int i = 0;i < s.length();i++){
map[s.charAt(i)]++;
}
int count = 0;
for(int i = 0;i < s.length();i++){
if(map[s.charAt(i)] % 2 == 1){
count = 1;
}
}
for(int temp:map){
if(temp % 2 == 0){
count += temp;
}
if(temp > 2 && temp % 2 == 1){
count += temp - 1;
}
}
return count;
}
}