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.
翻译:给定一个由小写或大写字母组成的字符串,找到可以用这些字母构建的最长的回文长度。
这是区分大小写的,例如"Aa"
在这里不被视为回文。
注意:
假设给定字符串的长度不能超过1,010。
例:
输入: “abccccdd” 输出: 7 说明: 可以构建的最长的回文为“dccaccd”,长度为7。
思路:
第一次循环用HashMap来存s内不同字符和其数量和,第二次循环依次判断map中的value是否为2的倍数,若为2的倍数则length加其value,若不为则加value-1;并标记标志为1,因为有单个字符出现最后结果要加一。
public int longestPalindrome(String s) {
char[] s2a = s.toCharArray();
Map<Character,Integer> map = new HashMap<Character,Integer>();
int length = 0,flag = 0;
for(int i = 0; i<s2a.length;i++){
if(map.containsKey(s2a[i])){
int sum = map.get(s2a[i]);
sum++;
map.put(s2a[i],sum);
}else{
map.put(s2a[i],1);
}
}
for(Integer value : map.values()){
if(value % 2 == 0){
length += value;
}else if(value % 2 == 1){
flag = 1;
length += (value-1);
}
}
return length+flag;
}
答案思路:
使用HashSet,循环判断set中是否有当前字符,若有则删除该元素,count计数加1,若没有直接加入该元素。最后s内成对的元素个数为count*2,若map中还有剩余的元素,则长度还要加1。
public int longestPalindrome(String s) {
if(s==null || s.length()==0) return 0;
HashSet<Character> hs = new HashSet<Character>();
int count = 0;
for(int i=0; i<s.length(); i++){
if(hs.contains(s.charAt(i))){
hs.remove(s.charAt(i));
count++;
}else{
hs.add(s.charAt(i));
}
}
if(!hs.isEmpty()) return count*2+1;
return count*2;
}