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.
(假设给定字符串的长度不会超过1,010。)
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
题目大意:
给定一个由小写或大写字母组成的字符串,找到可以用这些字母构建的最长的回文长度。
这是区分大小写的,例如“Aa”在这里不被视为回文。
错误思路: 思路是错误的!!!!!!!
刚开始以为求最大回文串长度,遍历字符串,求出各个字母数量,将所有的偶数相加,最后加上最大的奇数即可
代码如下:
//错误
int longestPalindrome(string s) {//所有偶数加上一个最大的奇数
int tmp[123] = {0};//a~z 65-9 A~Z 97-122
int res=0;
for(int i=0; i<s.size(); i++){
tmp[s[i]] += 1;
}
for(int m=0; m<123; m++)//将所有数量为偶数的字母数量加起来
if(tmp[m]>0 && tmp[m]%2==0)
res += tmp[m];
int maxOddNumber = 0;//最大的 数量为奇数的字母 的数量
for(int n=0; n<123; n++)//将所有数量为奇数的字母数量加起来
if(tmp[n]>0 && tmp[n]%2==1)
if(tmp[n]>maxOddNumber)
maxOddNumber = tmp[n];
cout << "maxOddNumber=" << maxOddNumber << endl;
return res+maxOddNumber;
}
正确思路: 思路是正确的!!!!!!!
回文串除中间字母外前后对称,也就是说,除了中间的字母外,其余的字母在回文中的数量必须是偶数。
发现奇数-1就是偶数,也能算到最大回文串长度中!
最大回文串长度 = 所有的偶数 + 所有的(奇数-1) + 1(有奇数+1 ,没奇数不加)
代码如下:
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
//正确
int longestPalindrome(string s) {//所有偶数+所有(大于1的奇数-1变成偶数)+1(有奇数+1 ,没奇数不加)
int tmp[123] = {0};//a~z 65-9 A~Z 97-122
int res=0;
for(int i=0; i<s.size(); i++){
tmp[s[i]] += 1;
}
bool a = false;//判断是否有奇数
for(int m=0; m<123; m++){//将所有数量为偶数的字母数量加起来
if(tmp[m]>0 && tmp[m]%2==0)
res += tmp[m];
if(tmp[m]>0 && tmp[m]%2==1){//所有的奇数-1变成偶数
a = true;
res = res + (tmp[m]-1);
}
}
return a ? res+1 : res;//有奇数+1 ,没奇数不加
}
};
int main()
{
Solution a;
string s;
//cin >> s;
s="civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
cout << a.longestPalindrome(s) << endl;//应该是983
return 0;
}