LeetCode Solutions
409. Longest Palindrome
Time: $O(n)$ Space: $O(128) = O(1)$
class Solution {
public:
int longestPalindrome(string s) {
int ans = 0;
vector<int> count(128);
for (const char c : s)
++count[c];
for (const int c : count)
ans += c % 2 == 0 ? c : c - 1;
const bool hasOddCount =
any_of(begin(count), end(count), [](int c) { return c & 1; });
return ans + hasOddCount;
}
};
class Solution {
public int longestPalindrome(String s) {
int ans = 0;
int[] count = new int[128];
for (final char c : s.toCharArray())
++count[c];
for (final int c : count)
ans += c % 2 == 0 ? c : c - 1;
final boolean hasOddCount = Arrays.stream(count).anyMatch(c -> c % 2 == 1);
return ans + (hasOddCount ? 1 : 0);
}
}
class Solution:
def longestPalindrome(self, s: str) -> int:
ans = 0
count = Counter(s)
for c in count.values():
ans += c if c % 2 == 0 else c - 1
hasOddCount = any(c % 2 == 1 for c in count.values())
return ans + hasOddCount