LeetCode-409. Longest PalindromeLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/longest-palindrome/
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.
Example 1:
Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase English letters only.
class Solution {
public:
int longestPalindrome(string s) {
unordered_map dict;
for (auto x : s) {dict[x] += 1;}
int length = 0, one_count = 0 ;
for (auto it = dict.begin(); it != dict.end(); it++) {
if (it->second % 2 == 0) {length += it->second;}
else {
if (it->second != 1) {length = length +(it->second-1);}
++one_count;
}
}
if (one_count > 0) {return length + 1;}
return length;
}
};
【Java】
class Solution {
public int longestPalindrome(String s) {
Map dict = new HashMap<>();
for (char ch : s.toCharArray()) {dict.put(ch, dict.getOrDefault(ch, 0) + 1);}
int length = 0, oneCount = 0;
for (Character ch : dict.keySet()) {
int cnt = dict.get(ch);
if (cnt % 2 == 0) {length += cnt;}
else {
if (cnt > 1) {length += cnt - 1;}
oneCount++;
}
}
if (oneCount > 0) {return length + 1;}
return length;
}
}
参考文献
【1】C++中的unordered_map用法详解_zou_albert的博客-CSDN博客
【2】java中遍历字符串的三种方式(String类的方法)_KD____的博客
【3】Java中遍历Map集合的5种方式总结_菜鸟是大神的博客-CSDN博客
【4】哈希表Hash与JAVA集合类Map及其方法put()、getOrDefault()、keySet()、get()
【5】java.util.Map中的putIfAbsent、computeIfAbsent、computeIfPresent、compute的区别


![LeetCode-409. Longest Palindrome [C++][Java] LeetCode-409. Longest Palindrome [C++][Java]](http://www.mshxw.com/aiimages/31/1034956.png)
