给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。
数据是大小写敏感的,也就是说,“Aa” 并不会被认为是一个回文串。
样例
样例 1:
输入 : s = "abccccdd"
输出 : 7
说明 :
一种可以构建出来的最长回文串方案是 "dccaccd"。
注意事项
假设字符串的长度不会超过 1010。
思路:建立一个数组并初始化为0,搜索每个字母出现次数,在建立一个bool类型来判断是否有单次数的字符的出现,再建立一个result储存偶数字符个数,注意result+=count[i]/2*2,最后如果bool=true,result+1。
class Solution {
public:
/**
* @param s: a string which consists of lowercase or uppercase letters
* @return: the length of the longest palindromes that can be built
*/
int longestPalindrome(string &s) {
// write your code here
int len=s.size();
int count[60]={0};
for (int i = 0; i < len; i++) {
/* code */
count[s[i]-'A']++;
}
bool judge=false;
int result=0;
for (int i = 0; i < 60; i++) {
/* code */
if(count[i]%2==1) judge=true;
result+=count[i]/2*2;
}
if(judge) return result+1;
else return result;
}
};