原题:
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.
tips:
- 给出一串字符串,然后取这串字符串的字符组成一个新的回文字符串,求回文字符串的最长长度;
- 字符串中的字母的个数为奇数的取这个奇数减一,字母的个数为偶数的取这个偶数,最后,如果这个字符串包含个数为奇数的字母还要再加一;
- 有两种方式,一种方式使用hashmap(运行时间为25ms),另外一种方式使用hasSet(运行时间是20ms),两种方法实质上是一样的,都弄出来,多种思路吧;
方式一:hashMap方式;
public int longestPalindrome(String s) {
if(s.length()<=0||s==null)
return 0;
if(s.length()==1)
return 1;
HashMap<Character,Integer> hashMap=new HashMap<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(hashMap.containsKey(c))
hashMap.put(c,hashMap.get(c)+1);
else
hashMap.put(c,1);
}
int flag=0;
int res=0;
Set<Map.Entry<Character,Integer>> entry=hashMap.entrySet();
for(Map.Entry<Character,Integer>e:entry){
if(e.getValue()%2==0)
res+=e.getValue();
else
{
res+=e.getValue()-1;
flag=1;
}
}
res+=flag;
return res;
方式二:hashSet方式
public int longestPalindrome(String s){
if(s.length()<=0||s==null)
return 0;
if(s.length()==1)
return 1;
HashSet<Character> hashSet=new HashSet<>();
int count=0;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(hashSet.contains(c))
{
hashSet.remove(c);
count++;
}
else {
hashSet.add(c);
}
}
count=hashSet.size()==0?count*2:count*2+1;
return count;
}