Longest Palindrome Problem
Description
LeetCode Problem 409.
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindromethat can be built with those letters.
Letters are case sensitive, for example,”Aa” is not considered a palindrome here.
Example 1:
1
2
3
4
Input: s = "abccccdd"
Output: 7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
1
2
Input: s = "a"
Output: 1
Example 3:
1
2
Input: s = "bb"
Output: 2
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase Englishletters only.
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<int,int> mp;
int res = 0;
for (int i = 0; i < s.length(); i++) {
mp[s[i]] ++;
if (mp[s[i]]%2 == 0) {
res += mp[s[i]];
mp[s[i]] = 0;
}
}
for (auto x: mp) {
if (x.second == 1) {
res ++;
break;
}
}
return res;
}
};