Problem
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.
Notice
Assume the length of given string will not exceed 1010.
Example
Given s = "abccccdd" return 7
One longest palindrome that can be built is "dccaccd", whose length is 7.
Solution
public class Solution {
/*
* @param s: a string which consists of lowercase or uppercase letters
* @return: the length of the longest palindromes that can be built
*/
public int longestPalindrome(String s) {
// write your code here
int res = 0;
//Use HashMap to store occurrence, when it's even, res adds 2 and map deletes the key
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
map.remove(ch);
res += 2;
} else {
map.put(ch, 1);
}
}
if (res < s.length()) res += 1;
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。