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.
题意:
现给出一个字符串s,利用s中字符,求出最长回文字符串(回文串类似:aabcc)的长度,并返回。
分析:
- 这里是要求出最长回文子串的长度,而不是求出最长回文子串
- 当字符串中字符出现次数为偶数时,必然可以加入最长回文子串
- 当字符串中字符出现次数为奇数时,分情况讨论:
- 如果出现次数为大于1的奇数n,则可以加入n-1个对应字符到最长回文子串
- 最终的最长回文子串,最中间还可以加入一个单一字符
- 上面两条合并起来,即可以直接将出现最大奇数次数的字符都加入最长回文子串
- 即if(出现奇数次数的字符数==0),return s.length()
- if(出现奇数次数的字符数!=0),return s.length()- 出现奇数次数的字符数+1
public class Solution {
public int longestPalindrome(String s) {
//将字符串s转换成字符数组chars[]
char chars[]=s.toCharArray();
//分别申明数组保存各个大小写字母(共26个)出现的次数
int lower[]=new int[26];
int upper[]=new int[26];
//保存字符数组中字符出现奇数次的次数
int odds=0;
//循环将chars数组对应大小写字符出现次数保存在对应次数数组中
for(int i=0;i<s.length();i++){
//如果chars数组中字符为大写字符
if(chars[i]<'a'){
//按照字符大小顺序对应保存大写字符出现次数
upper[chars[i]-'A']++;
}
//如果chars数组中字符为小写字符
else{
//按照字符大小顺序对应保存小写字符出现次数
lower[chars[i]-'a']++;
}
}
//遍历保存大小写字符出现次数的数组
for(int j=0;j<26;j++){
//如果大写字符中存在出现次数为奇数次的字符,odds+1
if(upper[j]%2!=0)
odds++;
//如果小写字符中存在出现次数为奇数次的字符,odds+1
if(lower[j]%2!=0)
odds++;
}
//如果s中没有出现次数为奇数的字符,返回字符串长度即可
if(odds==0)
return s.length();
//否则,返回字符串长度-出现次数为奇数的字符个数+1
//即保留出现最大奇数次数的字符
else
return s.length()-odds+1;
}
}