LeetCode 409. Longest Palindrome

来源:互联网 发布:环绕音乐制作软件 编辑:程序博客网 时间:2024/06/01 13:22

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.


题目思路:

给定一个字符串,规定可以把字符串拆分成一个一个对字符,求出能组成的回文串的最大长度。

在回文串中,除了中间的一个字符可以是1个,别的字母必定是偶数个。

那么我们要求的回文串就有两种情况。

1.回文串的长度是奇数,中间有1个只出现一次的字符。

2.回文串的长度是偶数。

我们按照第2种情况求出回文串最长的长度,如果长度和给定字符串长度一样,那么这个长度必定是最长的。

如果小于给定的字符串的长度,那么他的中间一定还能再放一个字符,那么最长的长度就是当前长度+1。


题目代码:

class Solution {public:    int longestPalindrome(string s) {        int ans = 0;        map<char,int>table;        map<char,int>::iterator it;        for(int i = 0; i < s.length(); i++){            table[s[i]]++;        }        it = table.begin();        while(it != table.end()){            ans+=it->second/2;            it++;        }        return ans*2==s.length() ? ans*2 : ans*2+1;    }};

原创粉丝点击