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.
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.
题意:给定一个字符串,计算利用字符串中的所有字符可以组成的最长的回文串;
解法:回文串的形式只有两种可能的形式,字符串的长度为偶数和奇数的情况
- abccba
- abcdcda
所以,我们利用哈希表map统计字符串出现的次数后
- 遍历哈希表的所有键key
- 回文串的长度加上map.get(key) / 2 * 2(每两个相同字符回文串长度加2)
- 标记是否有map.get(key) % 2 == 1的字符,即考虑字符串长度为奇数的情况
Java
class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int res = 0;
boolean oneTimesChar = false;
for (int i = 0; i != s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (char c: map.keySet()) {
res += (map.get(c) / 2) * 2;
if (map.get(c) % 2 == 1) {
oneTimesChar = true;
}
}
return oneTimesChar ? res + 1 : res;
}
}