leetcode-409. 最长回文串

题目

https://leetcode-cn.com/problems/longest-palindrome/

解法

  1. 先理解回文串的定义
  2. 假设有 m 对字符,根据回文串的定义可得
    1. 全部两两成对之后,那就是 2*m
    2. 非两两成对,最后可以在中间放一个,那就是 2*m + 1
class Solution {
    
    /**
     * @param String $s
     * @return Integer
     */
    function longestPalindrome($s) {
        if (empty($s)) {
            return 0;
        }
        
        $retNum = 0;
        
        $mapS = [];
        for ($i = 0; $i < strlen($s); $i++) {
            $mapS[$s[$i]]++;
        }
    
        foreach ($mapS as $count) {
            $retNum += floor($count/2) * 2;
        }
        
        if ($retNum < strlen($s)) {
            $retNum++;
        }
        
        return $retNum;
    }
}
原文地址:https://www.cnblogs.com/wudanyang/p/15018126.html