[LeetCode] Longest Palindrome

409. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int longestPalindrome(string s) {
vector<int> counter(128,0);
for(auto ch : s) counter[ch]++;

int res = 0;
for(auto n : counter) {
if(n&1 and !(res&1)) res++;
res += n / 2 * 2;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/longest-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.