Longest Palindrome
lc409
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.
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
题目是给出一些字符,让你看看能形成最长多长的palindrome,顺序是打乱的。这样非常简单,hashtable纪录每个character出现的数目,最后到了2个就可以remove了,这样最后只需要返回count或者count+map的数目
public class Solution {
public int longestPalindrome(String s) {
if(s == null || s.length() == 0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int count = 0;
for(int i = 0; i < s.length(); i++ ){
if(map.containsKey(s.charAt(i))){
count = count + 2;
map.remove(s.charAt(i));
}else{
map.put(s.charAt(i), 1);
}
}
return map.size() == 0? count: count + 1;
}
}