Skip to content

409. Longest Palindrome #148

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jul 30, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can use a hash table to count the occurrences of each character. The key insight here is:

  1. Characters that appear an even number of times can fully contribute to the palindrome.
  2. Characters that appear an odd number of times can contribute up to the largest even number that is less than or equal to their count. However, you can use one odd character as the center of the palindrome, so we can add 1 to the final length if there's at least one character with an odd count.

Let's implement this solution in PHP: 409. Longest Palindrome

<?php
/**
 * @param String $s
 * @return Integer
 */
function longestPalindrome($s) {
    $charCount = [];
    $length = 0;
    $oddCountFound = false;

    /…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@topugit
Comment options

topugit Aug 30, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Aug 30, 2024
Maintainer Author

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants