问题描述:
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome here.
解释:s里面的字符,如何重组成一个最长的回文字符串,区分大小写。
思路:
思路很简单,用哈希表统计字符出现的次数。如果一个字符出现偶数次,则全部累加到counter里;若出现奇数次,则累加“次数减一”次。稍微值得注意的是,即使是回文字符串,正中间的那一个字符(长度为奇数)也可以是不配对的,这个仅有的特殊的机会可以留给任意一个出现奇数次的字符,但记住,这个机会只有一次
代码如下:
class Solution {
public int longestPalindrome(String s) {
int counter=0;
boolean aSpecialChance=true;
Map<Character, Integer> map=new HashMap<>();
for(int i=0; i<s.length(); i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i), 1);
}
else{
map.put(s.charAt(i), map.get(s.charAt(i))+1);
}
}
for(Character ch: map.keySet()){
if (map.get(ch)%2==0){
counter=counter+map.get(ch);
}
else{
counter=counter+map.get(ch)-1;
aSpecialChance=false;
}
}
return (aSpecialChance==true)? counter: counter+1 ;
}
}
时间复杂度: O(n)