Skip to content

409. Longest Palindrome 👍

  • Time: $O(n)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int longestPalindrome(string s) {
    int ans = 0;
    vector<int> count(128);

    for (const char c : s)
      ++count[c];

    for (const int freq : count)
      ans += freq % 2 == 0 ? freq : freq - 1;

    const bool hasOddCount =
        ranges::any_of(count, [](int c) { return c % 2 == 1; });
    return ans + hasOddCount;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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 freq : count)
      ans += freq % 2 == 0 ? freq : freq - 1;

    final boolean hasOddCount = Arrays.stream(count).anyMatch(freq -> freq % 2 == 1);
    return ans + (hasOddCount ? 1 : 0);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def longestPalindrome(self, s: str) -> int:
    ans = 0
    count = collections.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