LeetCode 409 Longest Palindrome

Problem:

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.

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.

Summary:

给出一个可能包含大写、小写字母的字符串,求用字符串中的字母可组成的最长回文串长度。此处大写、小写字母视为有区别。

Analysis:

1. 回文串包含两种形式:aba形式及aaa形式。在给出的字符串中,所有出现次数为偶数的字母都可以用为回文串中;若有出现次数为奇数的字母,则先将其包含的最大偶数次加入回文串长度中(即奇数次数减1),再在最后加上放在最中间的一个字母。下面为Hash表映射字母和出现次数的方法。

 1 class Solution {
 2 public:
 3     int longestPalindrome(string s) {
 4         int len = s.size(), ch[52] = {0}, res = 0;
 5         bool odd = false;
 6         
 7         for (int i = 0; i < len; i++) {
 8             if (s[i] >= 'a' && s[i] <= 'z') {
 9                 ch[s[i] - 'a']++;
10             }
11             else {
12                 ch[s[i] - 'A' + 26]++;
13             }
14         }
15         
16         for (int i = 0; i < 52; i++) {
17             if (ch[i] % 2 == 0) {
18                 res += ch[i];
19             }
20             else {
21                 odd = true;
22                 res += ch[i] - 1;
23             }
24         }
25         
26         return odd ? res + 1 : res;
27     }
28 };

2. 如上已分析,得到的回文串长度为原字符串中所有出现偶数次的字母次数,以及出现奇数次的字母次数中的最大偶数,最终再加上回文串中间的一个字母(有奇数次字母时)。

这个结果相当于在原字符串中,将每一个出现奇数次的字母减掉一个,最终加上回文串中间的字母。下面的代码用count统计每个字母出现的次数,和1作&操作来判断是否为奇数。

 1 class Solution {
 2 public:
 3     int longestPalindrome(string s) {
 4         int odd = 0, len = s.size();
 5         for (int i = 0; i < 26; i++) {
 6             char c = i + 'a';
 7             odd += count(s.begin(), s.end(), c) & 1;
 8         }
 9         
10         for (int i = 0; i < 26; i++) {
11             char c = i + 'A';
12             odd += count(s.begin(), s.end(), c) & 1;
13         }
14         
15         return odd ? len - odd + 1 : len;
16     }
17 };
原文地址:https://www.cnblogs.com/VickyWang/p/6010117.html