Easy
61164FavoriteShare
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:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
C++:
/*
* @Autor: SourDumplings
* @Date: 2019-09-23 15:17:44
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/longest-palindrome/
*
* 回文序列中奇数个数的元素只能最多有一个
*/
class Solution
{
public:
int longestPalindrome(string s)
{
int A[200];
fill(A, A + 200, 0);
for (auto &&c : s)
{
++A[c - 'A'];
}
bool isFirstOdd = true;
int res = 0;
for (int i = 0; i < 200; i++)
{
if (A[i] & 1)
{
if (isFirstOdd)
{
res += A[i];
isFirstOdd = false;
}
else
{
res += A[i] - 1;
}
}
else
{
res += A[i];
}
}
return res;
}
};
Java:
import java.util.Arrays;
/*
* @Autor: SourDumplings
* @Date: 2019-09-23 15:55:05
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/longest-palindrome/
*/
class Solution
{
public int longestPalindrome(String s)
{
int[] A = new int[200];
int l = s.length();
Arrays.fill(A, 0);
for (int i = 0; i < l; i++)
{
++A[s.charAt(i) - 'A'];
}
int res = 0;
boolean isFirstOdd = true;
for (int i = 0; i < 200; i++)
{
if ((A[i] & 1) == 1)
{
if (isFirstOdd)
{
res += A[i];
isFirstOdd = false;
}
else
{
res += A[i] - 1;
}
}
else
{
res += A[i];
}
}
return res;
}
}