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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值