LeetCode 409 & LintCode 627
Description: 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.
Example:
Input : s = "abccccdd"
Output : 7
Explanation : One longest palindrome that can be built is "dccaccd", whose length is `7`.
Thinking Mode: HashMap
- make sure the input string is a valid string.
- Using HashMap structure to save every character in the string and the corresponding values, which is number of times it occurs in the string. If the corresponding value reaches 2, reset it to 0 and the longest length +2.
- After traversing all the characters, if the longest is less than the length of the original string, which means there is odd number of characters. Then the longest length needs to +1. (HashSet works similar as HashMap)
- Time Complexity: O(n)
- Other method: Greedy Method
Example: s = "abccdd"
Java Solution
public class Solution {
/**
* @author: Demi
* @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) {
int len = s.length();
if (len == 0 || s == null) {
return 0;
}
Map<Character, Integer> map = new HashMap<>();
int longest = 0;
for (int i = 0; i < len; i++) {
char curr = s.charAt(i);
if (map.containsKey(curr) == false) {
map.put(curr, 1);
}
else {
int value = map.get(curr) +1;
if (value == 2){
map.put(curr, 0);
longest += 2;
}
else {
map.put(curr, value);
}
}
}
if (longest < len) {
return longest+1;
}
else {
return longest;
}
}
}