Question:
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 = "abccccddaa"可生成的最长回文字符串长度为9,如ddccaaaccd,acdcacdca等都正确。
思路:
采用字符hash方法,统计字符串中所有字符数量。
若某个字符个数为偶数,则全部可以用来构成回文串。
若某个字符个数为奇数,则(总个数-1)个可以用来构成回文串,并且设置一个flag变量,存在奇数个某字符的时候,可以选择一个作为中心字符,即回文串长度+1。
class Solution {
public int longestPalindrome(String s) {
int [] char_map = new int[128]; //建立字符hash表,存储每个字符的个数
int flag = 0; //判断string中的每个字符个数是否为奇数,若为奇数,则flag=1;
int result = 0;
for(int i = 0; i<s.length();i++)
char_map[s.charAt(i)]++;
for(int i = 0; i<char_map.length;i++)
{
if(char_map[i]%2==0)//若某个字符个数为偶数,全部可以用来构成回文串,长度直接加入result
result = result + char_map[i];
else
{
result = result + char_map[i]-1;
flag = 1; //若某个字符个数为偶数,长度-1可以用来构成回文串,并且flag置1,可以选择某一个作为中心字符
}
}
if(flag==1)
return result+1;
else
return result;
}
}
博主学习笔记,转载请注明出处,谢谢~