409. Longest Palindrome #148
-
Topics: Given a string Letters are case sensitive, for example, Example 1:
Example 2:
Constraints:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a hash table to count the occurrences of each character. The key insight here is:
Let's implement this solution in PHP: 409. Longest Palindrome <?php
/**
* @param String $s
* @return Integer
*/
function longestPalindrome($s) {
$charCount = [];
$length = 0;
$oddCountFound = false;
// Count the occurrences of each character
for ($i = 0; $i < strlen($s); $i++) {
$char = $s[$i];
if (!isset($charCount[$char])) {
$charCount[$char] = 0;
}
$charCount[$char]++;
}
// Calculate the length of the longest palindrome
foreach ($charCount as $count) {
if ($count % 2 == 0) {
// Add the entire count if it's even
$length += $count;
} else {
// Add the largest even number less than count
$length += $count - 1;
$oddCountFound = true;
}
}
// If there was at least one character with an odd count, we can place one in the middle
if ($oddCountFound) {
$length += 1;
}
return $length;
}
// Example usage:
$solution = new Solution();
echo $solution->longestPalindrome("abccccdd"); // Output: 7
echo $solution->longestPalindrome("a"); // Output: 1
?> Explanation:
This approach ensures an optimal solution with a time complexity of O(n), where n is the length of the string |
Beta Was this translation helpful? Give feedback.
We can use a hash table to count the occurrences of each character. The key insight here is:
Let's implement this solution in PHP: 409. Longest Palindrome