LeetCode 409. Longest Palindrome

来源:互联网 发布:ubuntu切换到windows 编辑:程序博客网 时间:2024/06/07 22:25

409. 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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.

三、解题思路

  • 要找到最长的回文串长度。回文串是指正着反着都是一样的。所以字符全部都是成对出现的,除了中间那一个。所以就可以用一个map来保存下每个字符出现的次数,然后有出现偶数次的直接都放到回文串里,如果出现基数,分为两种情况大于2的基数1 中间这个单数我们首选前者,这样可以直接处理掉像是xxx这种输入,如果没有大于2的基数这种情况出现,那么我们在处理某个字符只出现1次,把他放到回文串的中间即可。如果上述两种情况都没出现,那么就返回全是偶数的结果即可。
class Solution {public:    int longestPalindrome(string s) {        map<char, int> dict;        int n = s.size();        for (int i = 0; i < n; ++i) {            char ch = s.at(i);            if(dict.find(ch) == dict.end()) dict[ch] = 1;            else dict[ch]++;        }        int ret = 0;        for (auto ite : dict){            int cnt = ite.second;            ret += cnt - cnt % 2;        }      //单独处理像:ccc 这种情况        for (auto ite : dict){            int cnt = ite.second;            if(cnt > 2 && cnt % 2 == 1) return (++ret);        }      //单独处理:aabbc 这种情况        for (auto ite : dict){            int cnt = ite.second;            if(cnt == 1) return(++ret);        }        return ret;    }};
原创粉丝点击