Leetcode_409_Longest Palindrome

Longest Palindrome

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

这题就是求,用题目中所给字符串中的字符,可以生成的最长回文串的长度。

算法思路:

  1. 利用字符哈希方法统计字符创中所有字符的数量
  2. 设最长回文字符串偶数长度为max_length = 0
  3. 设置是否有中心点标记flag = 0
  4. 遍历每一个字符,字符数为count,若count为偶数max_length += count,若count为奇数,max_length += count - 1, f1ag = 1
  • 最终最长回文字串长度为max_length + flag
class Solution {
public:
    int longestPalindrome(std::string s) {
        int char_map[128] = {0};
        int max_length = 0;
        int flag = 0;
        for (int i = 0; i < s.length(); i++){
            char_map[s[i]]++;
        }
        for (int i = 0; i < 128; i++){
            if (char_map[i] % 2 == 0){
                max_length += char_map[i];
            }
            else{
                max_length += char_map[i] - 1;
                flag = 1;
            }
        }
        return max_length + flag;
    }
};
上一篇:Python回文


下一篇:Photoshop为冬季图片增加影视中的雪花效果