D116 409. Longest Palindrome
Topic link
409. Longest Palindrome
Subject analysis
Returns the longest palindrome string length that can be formed from a given string.
Train of thought
Count the number of occurrences with array_count_values. And distinguish between even and odd occurrences of the letter. Array_sum is a straightforward way to count the number of letters that occur even times. For an odd number of letters, only one can be included in the middle of the palindrome string. So we have to subtract n minus 1 from the sum. Where n is the number of letters with odd occurrences.
The final code
class Solution {
/ * * *@param String $s
* @return Integer
*/
function longestPalindrome($s) {
$s = str_split($s);
$amounts = array_count_values($s);
$total = 0;
$maxOdd = 0;
foreach($amounts as $v){
$total += $v;
if($v%2! =0){
$total -=1;
if($v > $maxOdd){ $maxOdd = $v; }}}if($maxOdd! =0){
$total+=1;
}
return$total; }}Copy the code
This scenario beat only 15.8% of the code. Subsequently, the following programme was used:
class Solution {
/ * * *@param String $s
* @return Integer
*/
function longestPalindrome($s) {
$s = str_split($s);
$amounts = array_count_values($s);
$odd = [];
$even = [];
array_walk($amounts, function($v, $k) use (&$odd, &$even){
if($v%2! =0){
$odd[$k] = $v;
}
else{ $even[$k] = $v; }}); $odds = count($odd);if(!empty($odds)){
$odds--;
}
$total = array_sum($even) + array_sum($odd) - $odds;
return$total; }}Copy the code
You beat 100%. Call it a day!
If you find this article useful, you are welcome to subsidize it with love.