码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode_409_Longest Palindrome

时间:2019-10-27 20:41:43      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:one   cee   hat   exce   rom   字符   note   sid   sts   

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;
    }
};

Leetcode_409_Longest Palindrome

标签:one   cee   hat   exce   rom   字符   note   sid   sts   

原文地址:https://www.cnblogs.com/lihello/p/11748540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!